简体   繁体   中英

Can I add Number of buttons in runtime depending on a variable and not in xml

I want to my activity to have the number of buttons depending on the array size given. Consider an array s1[4]. So the size is 4. I Would like to have 4 buttons in my activity.How could I achieve it?

You can dynamically add button in availbale linear layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


</LinearLayout>

MainActivity.java

public void addButton(){
       Button myButton = new Button(this);
       myButton.setText("Push Me");

       LinearLayout ll = (LinearLayout)findViewById(R.id.linear_layout);
       LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
       ll.addView(myButton, lp);
}

Add Dynamic Buttons to your LinearLayout

Try something like this

//the layout in which you want to add the button
LinearLayout layout = (LinearLayout) findViewById(R.id.your_lin_layout);

for(int i = 0; i<arrayName.length ; i++) {

    //create the button
    Button btn = new Button(this);

    //set all your button attributes, like text color,background color etc. here
    btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    btn.setText("YOUR BUTTON TEXT");

    //Set onClickListener
     btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // define this method in your activity
            onBtnClick(i);
        }
    });

    //add the button to your linear layout
    layout.addView(btn);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM