setOnClickListener 仅在 for 循环内抛出 NullPointerException。为什么?

发布于 2024-10-04 11:52:00 字数 637 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看春风乍起 2024-10-11 11:52:00

我认为这是因为您的 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文