我正在尝试显示按钮。但下面的代码不起作用。不幸的是,应用程序已停止。需要额外的代码吗?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
String[] values = { "GOogle", "Yahoo", "Twi" };
Button[] b = new Button[values.length];
for (int i = 1; i <= values.length; i++) {
b[i].setText(values[i]);
layout.addView(b[i]);
}
setContentView(layout);
}
最佳答案
在尝试调用 setText
之前,Button
数组的元素不会被实例化,这将导致 NPE。试试这个
for (int i=0; i < b.length; i++) {
b[i] = new Button(this); // create Button programmatically
}
另外,在Java中,数组是从零开始的,替换
for (int i = 1; i <= values.length; i++) {
与
for (int i = 0; i < values.length; i++) {
编辑:在这种情况下,您的b
和值
恰好长度相同,因此您可以将 2 个循环集成在一起。
关于java - 如何循环按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983623/