How to add a button dynamically in Android?

Android

Android Problem Overview


How to add a button dynamically in Android?

Android Solutions


Solution 1 - 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

Solution 2 - Android

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();
		}
	});
}

Solution 3 - Android

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);

Solution 4 - Android

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);
    }
}

Solution 5 - Android

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();
			}
		});
	}

Solution 6 - Android

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); 

Solution 7 - Android

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);

Solution 8 - Android

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);

Solution 9 - Android

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);
}
}

Solution 10 - Android

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");
				}
				
				
				
			}
		});
	}

}

Solution 11 - Android

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.

Solution 12 - Android

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);

Solution 13 - Android

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).

Solution 14 - Android

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();
            }
        });

Solution 15 - Android

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);
    }

}

Solution 16 - Android

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...

Solution 17 - Android

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.

Solution 18 - Android

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeepthiView Question on Stackoverflow
Solution 1 - AndroidnicoView Answer on Stackoverflow
Solution 2 - Androiddicklaw795View Answer on Stackoverflow
Solution 3 - AndroidNuuoeiZView Answer on Stackoverflow
Solution 4 - AndroidHarish KoonaView Answer on Stackoverflow
Solution 5 - AndroidtilakView Answer on Stackoverflow
Solution 6 - AndroidMercyView Answer on Stackoverflow
Solution 7 - AndroidRuchiran AvishkaView Answer on Stackoverflow
Solution 8 - AndroidveerendranView Answer on Stackoverflow
Solution 9 - Androiduser2790339View Answer on Stackoverflow
Solution 10 - Androiddroidster.meView Answer on Stackoverflow
Solution 11 - AndroidMr.SandyView Answer on Stackoverflow
Solution 12 - AndroidLiTTleView Answer on Stackoverflow
Solution 13 - AndroidWaveformDeltaView Answer on Stackoverflow
Solution 14 - AndroidJogendra GoudaView Answer on Stackoverflow
Solution 15 - AndroidVictor Ruiz.View Answer on Stackoverflow
Solution 16 - AndroidalexpfxView Answer on Stackoverflow
Solution 17 - AndroidFatherlyNickView Answer on Stackoverflow
Solution 18 - AndroidashwiniView Answer on Stackoverflow