How to add a button dynamically in Android? - android

How to add a button dynamically in Android?

Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Have a look to this example

try this:
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}

Try this:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);

for (int k = 1; k < 100; k++) {
TableRow row = new TableRow(this);
innerloop:
for (int l = 1; l < 4; l++) {
btn = new Button(this);
TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setWeightSum(12.0f);
tr.weight = 0;
btn.setLayoutParams(tr);
btn.setTextColor(a);
btn.setHeight(150);
btn.setWidth(150);
btn.setId(idb);
btn.setText("Button " + idb);
row.addView(btn);
}
}

try this
private void createLayoutDynamically(int n) {
for (int i = 0; i < n; i++) {
Button myButton = new Button(this);
myButton.setText("Button :"+i);
myButton.setId(i);
final int id_ = myButton.getId();
LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
layout.addView(myButton);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}

Try this code
Button btn=new Button(this);
btn.setId(btn);
btn.setBackgroundResource(R.drawable.image);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
Relativelayout.addView(btn);

Check this up.
LinearLayout ll_Main = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());
ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
final Button button01 = new Button(getActivity());
final Button button02 = new Button(getActivity());
final Button button03 = new Button(getActivity());
final Button button04 = new Button(getActivity());
ll_Row01.addView(button01);
ll_Row01.addView(button02);
ll_Row02.addView(button03);
ll_Row02.addView(button04);
ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);
button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);

Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);

Try this code. It will work fine..
public class DynamicViewsActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_dynamic_views);
ScrollView scrl=new ScrollView(this);
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(100, 500, 100, 200);
scrl.addView(ll);
Button add_btn=new Button(this);
add_btn.setText("Click Here");
ll.addView(add_btn, layoutParams);
final Context context = this;
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
this.setContentView(scrl);
}
}

Try following code.
LinearLayout layout = (LinearLayout) findViewById(R.id.llayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText("Button1");
layout.add(btn);
btn = new Button(this);
btn.setText(Button2);
layout.add(btn);
like this you add Buttons as per your requirements.

public void add_btn() {
lin_btn.setWeightSum(3f);
for (int j = 0; j < 3; j++) {
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.setMargins(10, 0, 0, 10);
params1.weight = 1.0f;
LinearLayout ll;
ll = new LinearLayout(this);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(params1);
final Button btn;
btn = new Button(DynamicActivity.this);
btn.setText("A"+(j+1));
btn.setTextSize(15);
btn.setId(j);
btn.setPadding(10, 8, 10, 10);
ll.addView(btn);
lin_btn.addView(ll);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==0)
{
txt_text.setText("Hii");
}else if(v.getId()==1)
{
txt_text.setText("hello");
}else if(v.getId()==2)
{
txt_text.setText("how r u");
}
}
});
}
}

Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.
Here is an example:
((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);

I've used this (or very similar) code to add several TextViews to a LinearLayout:
// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;
// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);
TextView tv;
for (int i = 0; i < namesLength; i++) {
// Grab the name for this "button"
final String name = names[i];
tv = new TextView(context);
tv.setText(name);
// TextViews CAN have OnClickListeners
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
label.setText("Clicked button for " + name);
}
});
nameButtons.addView(tv, params);
}
The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).

Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});

If you want to add dynamically buttons try this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 1; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText(" ");
layout.addView(btn);
}
}

You could create a base layout for your button and dynamically change only what is specific, like this project I made to run different exercises from a Material Design course I'm taking:
In this example, I use a preconfigured AppCompatButton:
layout_base_button.xml
<android.support.v7.widget.AppCompatButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn_base"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
style="#style/RaisedButton"
>
</android.support.v7.widget.AppCompatButton>
<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
<item name="android:textSize">11sp</item>
<item name="android:textStyle">bold</item>
</style>
And in the MainActivity I created some instances and changed what I need, like the button text and onClick event:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="udemy.android.materialdesign.MainActivity">
<LinearLayout
android:id="#+id/base_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout baseLayout = findViewById(R.id.base_layout);
baseLayout.addView(createButton("TextFields", baseLayout,
view -> startActivity(createIntent(TextFieldsActivity.class))
));
baseLayout.addView(createButton("Buttons", baseLayout,
view -> startActivity(createIntent(ButtonsActivity.class))
));
baseLayout.addView(createButton("Toolbar", baseLayout,
view -> startActivity(createIntent(ToolbarActivity.class))
));
}
private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);
btnBase.setText(text);
btnBase.setOnClickListener(onClickEvent);
return btnBase;
}
private Intent createIntent(Class<?> cls) {
return new Intent(this, cls);
}
}
Sorry for being late...

I needed to create buttons even more dynamically, not just in runtime but by pressing another button. So clicking this button will dynamically create more buttons under it. I recommend having a ScrollView on the activity or limit the number of clicks - so no buttons go offscreen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="675dp">
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/newItemButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout); //Screen layout
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button newItemButton = findViewById(R.id.newItemButton);
newItemButton.setText("Create new button");
newItemButton.setOnClickListener(new View.OnClickListener() {
int pressCount = 1; //Count how many times button was pressed
public void onClick(View v) {
newItemButton.setText("Button Clicked: "+pressCount);
createButton(pressCount, params, ll); //Click to create new button
pressCount++;
}
});
} //end of onCreate
public void createButton(int id, LinearLayout.LayoutParams inputParams, LinearLayout inputLL) {
Button outButton = new Button(this);
outButton.setId(id);
final int id_ = outButton.getId();
outButton.setText("Button " + id_);
inputLL.addView(outButton, inputParams);
}
}//end of AppCompatActivity
This will give you an activity with a button.
When you click on that button, you spawn a new button underneath it.
If you spawn so many that they do not fit on the screen, the scrollView will take care of that.

In mainactivity.xml write:
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:visibility="invisible"/>
In main.java write:
Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);

Related

Views don`t appear on the screen

Clicking on the button creates a view. Then I add this view to layout, but it doesn`t appear on the screen.
private ArrayList<EditText> viewArray = new ArrayList<EditText>();
String str = "text";
LinearLayout linLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
setContentView(linLayout, linLayoutParam);
Button btnAdd = new Button(this);
btnAdd.setText("Add EditText");
LinearLayout.LayoutParams vParams = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linLayout.addView(btnAdd, vParams);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewArray.add( new EditText(getApplicationContext()) );
viewArray.get(viewArray.size()-1).setText(str + viewArray.size());
viewArray.get(viewArray.size()-1).setId(viewArray.size());
LinearLayout.LayoutParams vParams2 = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linLayout.addView(viewArray.get(viewArray.size()-1), vParams2);
Toast.makeText(getApplicationContext(),"size: " + viewArray.size(), Toast.LENGTH_LONG).show();
}
});
}
}
The application is not closed, there is no error, the view simply does not appear

Adding onClick to buttons that are created programmatically

A TextView and Button are programmatically created and added to a pre-existing vertical layout making it look like a vertical list of views. These views are only created based off the user entering data into an edittext and that data being saved into an ArrayList.
How can I add an onClick function to my 'trash' buttons that are programmatically created that would allow them to remove the view they are associated with.
public static ArrayList<String> deckNameArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
for(int i = 0; i < deckNameArray.size(); i++)
{
LinearLayout layout = new LinearLayout(this);
if ((i % 2) == 0) {
layout.setBackgroundColor(Color.CYAN);
} else {
layout.setBackgroundColor(Color.WHITE);
}
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
layout.setPadding(10, 5, 10, 5);
layout.setWeightSum(5);
mainLayout.addView(layout);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 4f);
TextView deckName = new TextView(this);
deckName.setText(deckNameArray.get(i));
deckName.setTextColor(Color.BLACK);
deckName.setTextSize(18);
deckName.setGravity(Gravity.CENTER_VERTICAL);
deckName.setLayoutParams(textViewParams);
layout.addView(deckName);
LinearLayout.LayoutParams imageButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
ImageButton remove = new ImageButton(this);
remove.setImageResource(R.mipmap.trash);
if ((i % 2) == 0) {
remove.setBackgroundColor(Color.CYAN);
} else {
remove.setBackgroundColor(Color.WHITE);
}
remove.setLayoutParams(imageButtonParams);
layout.addView(remove);
}
remove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
See http://developer.android.com/reference/android/widget/Button.html
You can set a click listener on any View, using code similar to the sample below:
View myView;
myView.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
// TODO your logic here
}
}

How to put check box and button in linear layout side by side in Android?

This my code what I have written :
while (i.hasNext()){
Map.Entry me= (Map.Entry) i.next();
checkBox=new CheckBox(this.getActivity());
checkBox.setId(Integer.parseInt(me.getKey().toString()));
checkBox.setText(me.getValue().toString());
checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) linearMain.getLayoutParams();
params.width=250;
linearMain.addView(checkBox);
dltButton=new Button(this.getActivity());
dltButton.setTag(btnCounter);
btnCounter++;
dltButton.setText("Delete");
linearMain.addView(dltButton);
}
and the screen is like this.
I want one check box and one delete button side by side and next in the next row similar way.
How to implement it any idea?
ok try this, Ihave modified your code to basic logic.you Activity's layout file should be as follows
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout >
and then you activity should be
public class MainActivity extends AppCompatActivity {
LinearLayout mainContainer;
CheckBox checkBox;
Button dltButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainContainer = (LinearLayout) findViewById(R.id.mainContainer);
for (int i = 0; i < 5 ; i++){
checkBox=new CheckBox(this);
checkBox.setText("Text");
LinearLayout linearMain = new LinearLayout(this);
linearMain.setOrientation(LinearLayout.HORIZONTAL);
linearMain.setWeightSum(1.0f);
LinearLayout.LayoutParams half = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
linearMain.addView(checkBox, half);
dltButton=new Button(this);
dltButton.setTag("tag");
dltButton.setText("ffff");
linearMain.addView(dltButton, half);
mainContainer.addView(linearMain);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout);
layout.setOrientation(LinearLayout.VERTICAL);
String[] count = new String[] { "1", "2", "3" };
int checkbox_count = 3;
CheckBox checkBox;
for (int i = 0; i < checkbox_count; i++) {
LinearLayout horizontal_layout = new LinearLayout(this);
horizontal_layout.setOrientation(LinearLayout.HORIZONTAL);
horizontal_layout.setLayoutParams(new LinearLayout.LayoutParams(500, 80));
checkBox = new CheckBox(this);
checkBox.setText("checkbox " + count[i]);
horizontal_layout.addView(checkBox);
Button delete_btn = new Button(this);
delete_btn.setText("Delete");
horizontal_layout.addView(delete_btn);
layout.addView(horizontal_layout);
}
}

change color when tab on that button(selected) and get normal layout for other button

i am creating dynamic button in one horizontal LinearLayout. now need to change color in background when i selected and at that time other button will be change as normal default layout.
i already create like this:-
my code like that :-
for(int i=0;i<=5;i++)
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
final TextView btn = new TextView(activity);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
//btn.setBackgroundColor(Color.rgb(70, 80, 90));
new_addonprice_name.addView(btn, params);
btn.setOnClickListener(new OnClickListener() {
#SuppressLint("ResourceAsColor") #Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* new_addonprice_name.removeAllViews();
String aaa = updatebutton();*/
btn.setSelected(true);
Toast.makeText(activity, btn.getText().toString(), Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(R.color.black);
}
});
}
put _id in static context its for previously clicked view. also add color white on your res/values/color.xml
static int _id=-1;
here is the code..
LinearLayout lin = new LinearLayout(context);
lin.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
lin.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i <= 5; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
final TextView btn = new TextView(context);
btn.setId(i);
final int id_ = btn.getId();
Log.i("id",""+id_);
btn.setText("button " + id_);
// btn.setBackgroundColor(Color.rgb(70, 80, 90));
lin.addView(btn, params);
btn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceAsColor")
public void onClick(View v) {
// TODO Auto-generated method stub
/*
* new_addonprice_name.removeAllViews(); String aaa =
* updatebutton();
*/
if(_id != -1)
{
TextView tv = (TextView) findViewById(_id);
tv.setBackgroundResource(R.color.white);
}
_id = id_;
btn.setSelected(true);
Toast.makeText(context, btn.getText().toString(),
Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(R.color.black);
}
});
If I understood you correctly, you need the selectors.
<Button
android:id="#+id/imageButtonSelector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/new_button" />
res/drawable/new_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/button_pressed_yellow"
android:state_pressed="true" />
<item android:drawable="#drawable/button_focused_orange"
android:state_focused="true" />
<item android:drawable="#drawable/button_normal_green" />
</selector>
for(int i=0;i<=5;i++)
{
//final String check = "1";
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
final TextView btn = new TextView(activity);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
// btn.setBackgroundResource(R.drawable.tab_selector);
//btn.setBackgroundColor(Color.rgb(70, 80, 90));
new_addonprice_name.addView(btn, params);
btn.setOnClickListener(new OnClickListener() {
#SuppressLint("ResourceAsColor") #Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* new_addonprice_name.removeAllViews();
String aaa = updatebutton();*/
// btn.setSelected(true);\
//if(_id != -1)
for(int i=0;i<=5;i++)
{
TextView tv = (TextView)dialog.findViewById(i);
tv.setBackgroundColor(R.color.white);
}
// _id = id_;
Toast.makeText(activity, btn.getText().toString(), Toast.LENGTH_SHORT).show();
btn.setBackgroundColor(R.color.black);
}
});
}

refresh activity with dynamic content

I have an activity with some dynamic content.
For each item of an array, there is a different content (number of textViews, checkboxes, ..)
The user clicks on a "save" button and then the screen has to refresh itself to display the content of the next item.
I was wondering if it was a good practice to reload my activity like this :
Intent refresh = new Intent(this, conflictActivity.class);
startActivity(refresh)
finish()
instead of removing all the views in my layouts, etc ...
I think it's easier to reload it.
Is there another way to do it ?
EDIT : added Code.
public class ConflicFieldTest extends Activity {
private int nbField;
private int nbChecked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conflict);
final Button saveButton = (Button) findViewById(R.id.save);
final LinearLayout leftLayout = (LinearLayout) findViewById(R.id.leftLayout);
final LinearLayout rightLayout = (LinearLayout) findViewById(R.id.rightLayout);
final TextView fieldName = new TextView(this);
final LinearLayout editLayoutRight = new LinearLayout(this);
final LinearLayout editLayoutLeft = new LinearLayout(this);
final LinearLayout fieldRight = new LinearLayout(this);
final LinearLayout fieldLeft = new LinearLayout(this);
final ArrayList<String> allIdInConflict = getAllIdInConflict();
for (int i = 0; i < allIdInConflict.size(); i++) {
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
nbField = 0;
nbChecked = 0;
final Map<String, Object> fieldsInConflict = conflict
.conflictWithFields(memoAccountMap,
serverAccountMap, modifiedAccountMap);
for (Iterator<Map.Entry<String, Object>> field = fieldsInConflict
.entrySet().iterator(); field.hasNext();) {
final Map.Entry<String, Object> entry = field.next();
fieldName.setText(entry.getKey() + " : ");
final EditText[] editTextArrayRight = new EditText[fieldsInConflict
.size()];
final EditText[] editTextArrayLeft = new EditText[fieldsInConflict
.size()];
final CheckBox[] checkboxRight = new CheckBox[fieldsInConflict
.size()];
final CheckBox[] checkboxLeft = new CheckBox[fieldsInConflict
.size()];
checkboxRight[nbField] = new CheckBox(
ConflicFieldTest.this);
checkboxLeft[nbField] = new CheckBox(
ConflicFieldTest.this);
editLayoutLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setOrientation(LinearLayout.HORIZONTAL);
fieldRight.setOrientation(LinearLayout.VERTICAL);
fieldLeft.setOrientation(LinearLayout.VERTICAL);
rightLayout
.addView(
editLayoutRight,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
leftLayout
.addView(
editLayoutLeft,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editTextArrayRight[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayRight[nbField].setText((String) entry
.getValue());
editTextArrayRight[nbField].setTextColor(Color.BLACK);
editTextArrayRight[nbField].setFocusable(false);
editTextArrayRight[nbField].setClickable(false);
editTextArrayRight[nbField].setWidth(180);
editTextArrayRight[nbField].setPadding(0, 10, 0, 0);
editTextArrayLeft[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayLeft[nbField]
.setText((String) serverAccountMap.get(entry
.getKey()));
editTextArrayLeft[nbField].setTextColor(Color.BLACK);
editTextArrayLeft[nbField].setFocusable(false);
editTextArrayLeft[nbField].setClickable(false);
editTextArrayLeft[nbField].setWidth(180);
editTextArrayLeft[nbField].setPadding(0, 10, 0, 0);
final int i1 = nbField;
checkboxLeft[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
checkboxRight[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
editLayoutLeft.addView(fieldName);
editLayoutRight
.addView(
editTextArrayRight[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutLeft
.addView(
editTextArrayLeft[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutRight.addView(checkboxRight[nbField]);
editLayoutLeft.addView(checkboxLeft[nbField]);
nbField++;
}
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//save data & update UI
}
}
.execute(appState.getSessionName(), id, "getObjectOnServer");
}
}
Sorry for the code, it is a litle bit dirty (i have deleted some parts), i am reworking it.
int flag = 0;
public void updateUI() {
if(flag == 0) {
//your normal codes...
} else {
//display view with user given data
}
}
Call this function in oncreate. At first flag will be set to zero. When u enter the data in textview and tick checkboxes, update the flag with some value. Then on save Button click call this function again. Now flag is set. So it will display the updated UI.
I think this will give u an idea..

Categories

Resources