是否可以在运行时根据变量而不是在xml中添加按钮数量

时间:2019-07-18 18:08:00

标签: java android xml android-button

我希望我的活动中按钮的数量取决于给定的数组大小。考虑一个数组s1 [4]。大小为4。我想在活动中使用4个按钮。如何实现?

2 个答案:

答案 0 :(得分:1)

您可以按可用的线性布局动态添加按钮。

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

答案 1 :(得分:1)

将动态按钮添加到LinearLayout

尝试这样的事情

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