我对 Android 编程很陌生,我无法弄清楚为什么我的代码不会通过某一行。我有 26 张图片(字母表中的字母),我希望它们都在我点击它们时做一些事情,所以我设置了一个 for 循环来为每张图片设置一个 onclick 监听器。每当我在手机上运行它并查看日志猫时,它都会说我有一个空指针异常并崩溃。如果您查看下面的 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;