在多个ImageButton的for循环中安装Android onclicklistener

时间:2013-08-11 05:35:16

标签: android onclick nullpointerexception

我是Android编程的新手,我无法弄清楚为什么我的代码不能通过某一行。我有26张图片(字母表中的字母),我希望他们在点击它们时都能做些什么,所以我设置了一个for循环来为每一个设置一个onclick监听器。每当我在手机上运行它并查看日志cat时,它说我有一个空指针异常并崩溃。如果您查看下面的onCreate()方法,它将转到:

Log.d("LetterMenu Class", "for loop2");

但是,它永远不会到达

Log.d("LetterMenu Class", "for loop3");

Log.d("LetterMenu Class", "before switch");

这是在onClick()方法内...所以,显然有一些东西它不喜欢我设置OnClickListener的方式(我假设),但我似乎无法弄清楚它是什么是。你可以使用这样的数组设置OnClickListener吗?顺便说一下,在switch语句中有很多情况并且它正确关闭,我只是没有包含它来节省空间。感谢您的帮助。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class LetterMenu extends Activity implements OnClickListener{

    String[] buttonNames = {"aButton", "bButton", "cButton", "dButton", "eButton",
            "fButton", "gButton", "hButton", "iButton", "jButton", "kButton", "lButton",
            "mButton", "nButton", "oButton", "pButton", "qButton", "rButton", "sButton",
            "tButton", "uButton", "vButton", "wButton", "xButton", "yButton", "zButton"};
    ImageButton[] letterButtons = new ImageButton[26];
    Intent intent;
    int res_id;

    public void onCreate(Bundle savedInstanceState){
        Log.d("LetterMenu Class", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.letters);       

        for(int i = 0; i< 26; i++){
            res_id = getResources().getIdentifier(buttonNames[i], "id", getPackageName());
            Log.d("LetterMenu Class", "for loop");
            letterButtons[i] = (ImageButton) findViewById(res_id);
            Log.d("LetterMenu Class", "for loop2");
            letterButtons[i].setOnClickListener(LetterMenu.this);
            Log.d("LetterMenu Class", "for loop3");
        }
    }

    @Override
    public void onClick(View v) {
        Log.d("LetterMenu Class", "before switch");
        switch(res_id){
        case R.id.aButton:
            Log.d("LetterMenu Class", "onClick1");
            intent = new Intent(this, Letters.class);
            intent.putExtra("LETTER_CLICKED", 'a');
            break;

        case R.id.bButton:
            intent = new Intent(this, Letters.class);
            intent.putExtra("LETTER_CLICKED", 'b');
            break;

        case R.id.cButton:
            intent = new Intent(this, Letters.class);
            intent.putExtra("LETTER_CLICKED", 'c');
            break;

0 个答案:

没有答案