App force close when changing items in StringArray, Android? - android

right now I'm working on a app which changes items in StringArray on button clicks. I've implemented left and right buttons, when I click right button the item changes by right, when I press left the item changes to left. Up to here everything is fine, but when I click left button when the item is on Steve Jobs the app force closes. Any idea why this is happening?
Strings.xml:
<string name="sj">Steve Jobs</string>
<string name="mz">Mark Zuckerberg</string>
<string name="bg">Bill Gates</string>
<string name="lp">Larry Page</string>
<string-array name="gl">
<item>#string/sj</item>
<item>#string/mz</item>
<item>#string/bg</item>
<item>#string/lp</item>
</string-array>
MainActivity.java:
package com.example.theatremode;
import android.support.v7.app.ActionBarActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
int counter = 0;
TextView tv1;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
Resources res = getResources();
final String[] list = res.getStringArray(R.array.gl); // get the array
((TextView) findViewById(R.id.tv1)).setText(list[counter]); // set the
// initial
// message.
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx = (TextView) findViewById(R.id.tv1);
counter++;
if (counter >= list.length)
counter = 0;
tx.setText(list[counter]); // set the new message.
}
});
Resources res2 = getResources();
final String[] list2 = res2.getStringArray(R.array.gl); // get the array
((TextView) findViewById(R.id.tv1)).setText(list2[counter]);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx2 = (TextView) findViewById(R.id.tv1);
counter--;
if (counter >= list2.length)
counter = 0;
tx2.setText(list2[counter]); // set the new message.
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.theatremode.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:id="#+id/tv1"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_alignLeft="#+id/tv1"
android:text="Left" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="48dp"
android:layout_marginRight="14dp"
android:text="Right" />

Looks like you have a IndexOutOfBoundsException.
It's not obvious exactly what's going on here, but this might fix it:
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx2 = (TextView) findViewById(R.id.tv1);
counter--;
//if (counter >= list2.length)
//counter = 0;
if (counter < 0)
counter = list2.length - 1;
tx2.setText(list2[counter]); // set the new message.
}
});

Related

How to pass value from a method to another method

import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity implements OnValueChangeListener {
EditText push_ups, sit_ups;
NumberPicker np;
Button calculate;
final Context context = this;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calculate = (Button)findViewById(R.id.calculate);
push_ups = (EditText)findViewById(R.id.pushups);
sit_ups = (EditText)findViewById(R.id.situps);
np = (NumberPicker)findViewById(R.id.np1);
checkbox = (CheckBox)findViewById(R.id.checkbox);
String[] values = {"some array"};
np.setMaxValue(values.length-1);
np.setMinValue(0);
np.setDisplayedValues(values);
np.setWrapSelectorWheel(false);
//calculateButton runs when I click the "calculate" Button
calculateButton();
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(push_ups.getWindowToken(), 0);
}
public int calculatePushups() {
int pushupScore = 0;
int ageGroup = Integer.parseInt(null, np.getValue());
int pushupReps = Integer.parseInt(push_ups.getText().toString());
final int [][] pushupTable = {"some 2D array"};
if (pushupReps<= 60) {
pushupScore = pushupTable[pushupReps][ageGroup];
} else {
pushupScore = 60;
}
return pushupScore;
}
public int calculateSitups() {
final int [][] situpTable = {"some 2D array"};
return 0;
}
private void normalRun() {
}
private void specialRun() {
}
private void calculateRun() {
if (checkbox.isChecked()) {
specialRun();
}
else {
normalRun();
}
}
private void calculateScore() {
calculatePushups();
calculateSitups();
calculateRun();
}
public void calculateButton() {
final TextView pus = (TextView)findViewById(R.id.pushup_score);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_custom);
dialog.setTitle("Score");
I am trying to set the TextView to display the pushupScore here but it seems I am trying to pass a result from another method to this. I have no idea how to get it around still new with android,
//pus.setText(pushupScore);
pus.setText(String.valueOf(calculatePushups()));
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
Here's my dialog XML code:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Push-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/pushup_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.97"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Sit-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="2.4km Run: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Award: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/dialog_ok"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:lineSpacingExtra="5dp"
android:text="Ok" />
</LinearLayout>
you are returning the pushupScore in calculatePushups so just write:
pus.setText(String.valueOf(calculatePushups()));
And btw this is not a android mechanism, this is simple java return usage:
http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
You left out quite a bit of your code so I'm not sure where your problem is, but if you could follow these steps and let me know if you're getting any errors etc? Anyway, here is what you need to have:
Make sure your Activity implements OnClickListener:
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
//...
}
Within the activity's overridden onCreate() method, register the activity as the handler:
calculate = (Button)v.findViewById(R.id.dialog_ok);
calculate.setOnClickListener(this);
Within MainActivity, have the handler like so:
public void onClick(View v){
switch(v.getId(){
case R.id.dialog_ok:
push_ups.setText("" + calculatePushups());
break;
}
// ...
}
Perhaps you should change your EditText into a TextView, the EditText isn't necessary and might be causing problems?
Is this what you were after?

Android Button Disable and enable

Hello I have an android application i want to create something like a lock button to the prevent error click on any button in application i use this method and it work great in disable all button i like but i can not re-enable it again after this all i need is that when i press lock button again it re-enable button2 and button 3 again
This is the activity code
import android.support.v7.app.ActionBarActivity;
import android.app.ActionBar;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
public class AboutActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
addListenerOnButton();
}
Button button;
Button button2;
Button button3;
private void addListenerOnButton() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.lock);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button2.setEnabled(false); //button which u want to disable
button3.setEnabled(false); //button which u want to disable
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.about, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is layout code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.lock.AboutActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:text="Button" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="66dp"
android:enabled="true"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lock"
android:layout_centerVertical="true"
android:enabled="true"
android:text="Button" />
</RelativeLayout>
You can use isEnabled() and use "not" operator to lock and unlock. If it's not enabled, it'll enable and vice versa.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button2.setEnabled(!button2.isEnabled()); //button which u want to disable
button3.setEnabled(!button3.isEnabled()); //button which u want to disable
}
});

Why my Android application is eating so much RAM?

I have an Android application with a very simple main activity. It only has two buttons, one textview and one edittext field. I launch the main activity (I don't do anything, just launch it from app drawer), then I press home button to get to my home screen, go to settings > appmanager > running > cached background processes and there I see that my app is eating more RAM than other cached background processes, around 8 MB of RAM. Is it normal? Why is it eating more than other apps? This is my code:
MainActivity:
package com.example.myapp;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
long maxMemory = Runtime.getRuntime().maxMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
Log.i("ilog", "memoryClass: " + memoryClass);
Log.i("ilog", "maxMemory: " + maxMemory);
Log.i("ilog", "totalMemory: " + totalMemory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private Button button1;
private Button button2;
private TextView textView1;
private EditText editText1;
private ComponentName cn;
private String disable = "Disable app";
private String enable = "Enable app";
private int enabledState;
private PackageManager pm;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
button1 = (Button) rootView.findViewById(R.id.button1);
editText1 = (EditText) rootView.findViewById(R.id.editText1);
textView1 = (TextView) rootView.findViewById(R.id.textView1);
button2 = (Button) rootView.findViewById(R.id.button2);
cn = new ComponentName(getActivity(), CallReceiver.class);
pm = getActivity().getPackageManager();
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
button1.setText(disable);
} else {
button1.setText(enable);
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
button1.setText(enable);
} else {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
button1.setText(disable);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText1.getText().toString().length() > 0) {
Intent callImitateIntent = new Intent(getActivity(), CallReceiver.class);
callImitateIntent.putExtra(TelephonyManager.EXTRA_STATE, TelephonyManager.EXTRA_STATE_RINGING);
callImitateIntent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, editText1.getText().toString());
getActivity().sendBroadcast(callImitateIntent);
} else textView1.setText("Invalid incoming number");
}
});
return rootView;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Intent serviceStopIntent = new Intent(this, WindowService.class);
stopService(serviceStopIntent);
}
}
fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myapp.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/welcome" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:maxLength="12"
android:hint="#string/edittext1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/button2" />
</RelativeLayout>
So can anyone tell me why is it eating so much RAM? Thanks in advance!

Android Quote app, next and back buttons

Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}

Add and Remove Views in Android Dynamically?

How do I add and remove views such as TextViews from Android app like on the original stock Android contacts screen where you press a small icon on the right side of a field and it adds or deletes a field which consists of a TextView and an editTextView (from what I can see).
Any examples on how to achieve this?
ViewParents in general can't remove views, but ViewGroups can. You need to cast your parent to a ViewGroup (if it is a ViewGroup) to accomplish what you want.
For example:
View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);
Note that all Layouts are ViewGroups.
I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ
Layout
Basically you'll two xml layout files:
A horizontal LinearLayout row view with a TextEdit, a Spinner and an ImageButton for deletion.
A vertical LinearLayout container view with just a Add new button.
Control
In the Java code, you'll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.
Other tricks
Set android:animateLayoutChanges="true" in xml to enable animation
Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.
Source code
The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// Some visibility logic control here:
if (s.toString().isEmpty()) {
mAddButton.setVisibility(View.GONE);
deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
This is my general way:
View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
Hi You can try this way by adding relative layout and than add textview in that.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
(LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);
TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);
EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);
relative.addView(tv);
relative.addView(edittv);
Just use myView.setVisibility(View.GONE); to remove it completely.
But if you want to reserve the occupied space inside its parent use myView.setVisibility(View.INVISIBLE);
Kotlin Extension Solution
Add removeSelf to directly call on a view. If attached to a parent, it will be removed. This makes your code more declarative, and thus readable.
myView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parent = parent as? ViewGroup ?: return
parent.removeView(this)
}
Here are 3 options for how to programmatically add a view to a ViewGroup.
// Built-in
myViewGroup.addView(myView)
// Reverse addition
myView.addTo(myViewGroup)
fun View?.addTo(parent: ViewGroup?) {
this ?: return
parent ?: return
parent.addView(this)
}
// Null-safe extension
fun ViewGroup?.addView(view: View?) {
this ?: return
view ?: return
addView(view)
}
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
For Adding the Button
LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);
For removing the button
ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);
Hi First write the Activity class. The following class have a Name of category and small add button. When you press on add (+) button it adds the new row which contains an EditText and an ImageButton which performs the delete of the row.
package com.blmsr.manager;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.blmsr.manager.R;
import com.blmsr.manager.dao.CategoryService;
import com.blmsr.manager.models.CategoryModel;
import com.blmsr.manager.service.DatabaseService;
public class CategoryEditorActivity extends Activity {
private final String CLASSNAME = "CategoryEditorActivity";
LinearLayout itsLinearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_editor);
itsLinearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category_editor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_delete:
deleteCategory();
return true;
case R.id.action_save:
saveCategory();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Adds a new row which contains the EditText and a delete button.
* #param theView
*/
public void addField(View theView)
{
itsLinearLayout.addView(tableLayout(), itsLinearLayout.getChildCount()-1);
}
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout() {
TableLayout tableLayout = new TableLayout(this);
tableLayout.addView(createRowView());
return tableLayout;
}
private TableRow createRowView() {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
EditText editText = new EditText(this);
editText.setWidth(600);
editText.requestFocus();
tableRow.addView(editText);
ImageButton btnGreen = new ImageButton(this);
btnGreen.setImageResource(R.drawable.ic_delete);
btnGreen.setBackgroundColor(Color.TRANSPARENT);
btnGreen.setOnClickListener(anImageButtonListener);
tableRow.addView(btnGreen);
return tableRow;
}
/**
* Delete the row when clicked on the remove button.
*/
private View.OnClickListener anImageButtonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TableRow anTableRow = (TableRow)v.getParent();
TableLayout anTable = (TableLayout) anTableRow.getParent();
itsLinearLayout.removeView(anTable);
}
};
/**
* Save the values to db.
*/
private void saveCategory()
{
CategoryService aCategoryService = DatabaseService.getInstance(this).getCategoryService();
aCategoryService.save(getModel());
Log.d(CLASSNAME, "successfully saved model");
Intent anIntent = new Intent(this, CategoriesListActivity.class);
startActivity(anIntent);
}
/**
* performs the delete.
*/
private void deleteCategory()
{
}
/**
* Returns the model object. It gets the values from the EditText views and sets to the model.
* #return
*/
private CategoryModel getModel()
{
CategoryModel aCategoryModel = new CategoryModel();
try
{
EditText anCategoryNameEditText = (EditText) findViewById(R.id.categoryNameEditText);
aCategoryModel.setCategoryName(anCategoryNameEditText.getText().toString());
for(int i= 0; i< itsLinearLayout.getChildCount(); i++)
{
View aTableLayOutView = itsLinearLayout.getChildAt(i);
if(aTableLayOutView instanceof TableLayout)
{
for(int j= 0; j< ((TableLayout) aTableLayOutView).getChildCount() ; j++ );
{
TableRow anTableRow = (TableRow) ((TableLayout) aTableLayOutView).getChildAt(i);
EditText anEditText = (EditText) anTableRow.getChildAt(0);
if(StringUtils.isNullOrEmpty(anEditText.getText().toString()))
{
// show a validation message.
//return aCategoryModel;
}
setValuesToModel(aCategoryModel, i + 1, anEditText.getText().toString());
}
}
}
}
catch (Exception anException)
{
Log.d(CLASSNAME, "Exception occured"+anException);
}
return aCategoryModel;
}
/**
* Sets the value to model.
* #param theModel
* #param theFieldIndexNumber
* #param theFieldValue
*/
private void setValuesToModel(CategoryModel theModel, int theFieldIndexNumber, String theFieldValue)
{
switch (theFieldIndexNumber)
{
case 1 :
theModel.setField1(theFieldValue);
break;
case 2 :
theModel.setField2(theFieldValue);
break;
case 3 :
theModel.setField3(theFieldValue);
break;
case 4 :
theModel.setField4(theFieldValue);
break;
case 5 :
theModel.setField5(theFieldValue);
break;
case 6 :
theModel.setField6(theFieldValue);
break;
case 7 :
theModel.setField7(theFieldValue);
break;
case 8 :
theModel.setField8(theFieldValue);
break;
case 9 :
theModel.setField9(theFieldValue);
break;
case 10 :
theModel.setField10(theFieldValue);
break;
case 11 :
theModel.setField11(theFieldValue);
break;
case 12 :
theModel.setField12(theFieldValue);
break;
case 13 :
theModel.setField13(theFieldValue);
break;
case 14 :
theModel.setField14(theFieldValue);
break;
case 15 :
theModel.setField15(theFieldValue);
break;
}
}
}
2. Write the Layout xml as given below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#006699"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.blmsr.manager.CategoryEditorActivity">
<LinearLayout
android:id="#+id/addCategiryNameItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/categoryNameTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_name"
android:textStyle="bold"
/>
<TextView
android:id="#+id/categoryIconName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/lbl_category_icon_name"
android:textStyle="bold"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/categoryNameEditText"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="#string/lbl_category_name"
android:inputType="textAutoComplete" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
<ImageButton
android:id="#+id/addField"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/addCategoryLayout"
android:src="#drawable/ic_input_add"
android:onClick="addField"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Once you finished your view will as shown below
//MainActivity :
package com.edittext.demo;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edtText;
private LinearLayout LinearMain;
private Button btnAdd, btnClear;
private int no;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtText = (EditText)findViewById(R.id.edtMain);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnClear = (Button)findViewById(R.id.btnClear);
LinearMain = (LinearLayout)findViewById(R.id.LinearMain);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
no = Integer.parseInt(edtText.getText().toString());
CreateEdittext();
}else {
Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
}
}
});
btnClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearMain.removeAllViews();
edtText.setText("");
}
});
/*edtText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});*/
}
protected void CreateEdittext() {
final EditText[] text = new EditText[no];
final Button[] add = new Button[no];
final LinearLayout[] LinearChild = new LinearLayout[no];
LinearMain.removeAllViews();
for (int i = 0; i < no; i++){
View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
text[i] = (EditText)view.findViewById(R.id.edtText);
text[i].setId(i);
text[i].setTag(""+i);
add[i] = (Button)view.findViewById(R.id.btnAdd);
add[i].setId(i);
add[i].setTag(""+i);
LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
LinearChild[i].setId(i);
LinearChild[i].setTag(""+i);
LinearMain.addView(view);
add[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
int a = Integer.parseInt(text[v.getId()].getText().toString());
LinearChild[v.getId()].removeAllViews();
for (int k = 0; k < a; k++){
EditText text = (EditText) new EditText(MainActivity.this);
text.setId(k);
text.setTag(""+k);
LinearChild[v.getId()].addView(text);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
// Now add xml main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtMain"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_weight="1"
android:ems="10"
android:hint="Enter value" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
<Button
android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:text="Clear" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" >
<LinearLayout
android:id="#+id/LinearMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
// now add view xml file..
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:ems="10" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:id="#+id/child_linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
</LinearLayout>

Categories

Resources