我写了一个简单的应用程序,我想在其中以编程方式添加一些按钮。问题是不确定必须添加多少按钮。我试图将“Button button = new Button”放入 for 循环中,因为我认为它只会创建一个局部变量。我想那是我的错;)
这是我的代码:
public class MainActivity extends Activity {
LinearLayout auswahl;
String element [] = new String [10]; //This is just an example, it would take many pages to show how this array gets created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auswahl = (LinearLayout)findViewById(R.id.LinearLayout2);
element [1] = "A";
element [2] = "B";
element [3] = "C";
element [4] = "D";
element [5] = "E";
element [6] = "F";
element [7] = "G";
element [8] = "H";
element [9] = "I";
element [0] = "J";
int anzahl = element.length;
for (int i = 0; i <= anzahl; i++){
schreibeButtons(i, element[i]);
}
}
public void schreibeButtons(int i, String string){
Button button = new Button(this);
button.setText(sortiment);
button.setWidth(auswahl.getWidth());
button.setHeight(40);
button.setId(i*100);
auswahl.addView(button);
} }
对我想要达到的目标有任何疑问吗?如何达到我的目标?