setOnClickListener 仅在 for 循环内抛出 NullPointerException。为什么?
private final Button[] BUTTONS = {
btn1, btn2, btn3,btn4
};
...
btn1 = (Button) this.findViewById(R.id.btn_1);
btn2 = (Button) this.findViewById(R.id.btn_2);
btn3 = (Button) this.findViewById(R.id.btn_3);
btn4 = (Button) this.findViewById(R.id.btn_4);
...
int n = BUTTONS.length;
for(int i=0; i<n; i++) {
if(DEBUG) Log.d(TAG, String.valueOf(i));
BUTTONS[i].setOnClickListener(this);
}
抛出 NullPointerException,而
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
工作正常。对我来说没有任何意义。
private final Button[] BUTTONS = {
btn1, btn2, btn3,btn4
};
...
btn1 = (Button) this.findViewById(R.id.btn_1);
btn2 = (Button) this.findViewById(R.id.btn_2);
btn3 = (Button) this.findViewById(R.id.btn_3);
btn4 = (Button) this.findViewById(R.id.btn_4);
...
int n = BUTTONS.length;
for(int i=0; i<n; i++) {
if(DEBUG) Log.d(TAG, String.valueOf(i));
BUTTONS[i].setOnClickListener(this);
}
throws NullPointerException, whereas
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
works fine. Doesn't make any sense to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是因为您的 Buttons 数组是在 btn1,... 仍为空时创建的。
因此,当您在循环中调用 BUTTONS[i].setOnClickListener 时,您实际上是在说 null.setOnClickListener ,这将给出异常。
尝试将数组设置为变量,然后在分配 btn1 等之后查看。
尚未测试,但类似的方法可能会更好...
private ArrayList mBtns = new ArrayList();
私有无效 initButton(int id) {
按钮 = (按钮) findViewById(id);
按钮.setOnClickListener(this);
mBtns.add(按钮);
...
initButton( R.id.btn_1
);
initButton(R.id.btn_2);
initButton(R.id.btn_3);
initButton(R.id.btn_4);
此外,除非按钮执行非常相似的操作,否则您可能会发现最好简单地在布局中的每个按钮上定义 onClick 属性,并节省大量编码(仅适用于 Android 1.6 及更高版本)。
I think it's because your Buttons array is created when btn1,... are still null.
So when you call BUTTONS[i].setOnClickListener in the loop you are really saying null.setOnClickListener which will give an exception.
Try setting up the array as a variable and sey AFTER you've assigned btn1, etc.
Haven't tested it but something like this might work better...
private ArrayList mBtns = new ArrayList();
private void initButton(int id) {
button = (Button) findViewById(id);
button.setOnClickListener(this);
mBtns.add(button);
}
...
initButton(R.id.btn_1);
initButton(R.id.btn_2);
initButton(R.id.btn_3);
initButton(R.id.btn_4);
Also unless the buttons do very similar things you may find it better to simply define the onClick attribute on each in the layout and save yourself A LOT of coding (only available in Android 1.6 and higher).