Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a button dynamically in Android?

Tags:

android

People also ask

How to dynamically create Button in Android?

This example demonstrates how do I add a button dynamically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


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