猿问

findViewById返回null

findViewById返回null

我有代码:

public class HelloWorld extends Activity {private Button buttonOk;private Button buttonCancel;private OnClickListener buttonOkListener = new OnClickListener() {
    public void onClick(View v){
        EditText editText = (EditText)findViewById(R.id.input);

        CharSequence textFromInput = (CharSequence) editText.getText();
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context,textFromInput,duration);
        toast.show();
    }};private OnClickListener buttonCancelListener = new OnClickListener() {
    public void onClick(View v){
        EditText editText = (EditText)findViewById(R.id.input);

        CharSequence textFromInput = (CharSequence) editText.getText();
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context,textFromInput,duration);
        toast.show();
    }};/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    // ToDo add your GUI initialization code here

    setContentView(R.layout.main);

    buttonOk = (Button)findViewById(R.id.buttonOk);
    buttonCancel = (Button)findViewById(R.id.buttonCancel);

    buttonOk.setOnClickListener(buttonOkListener);
    buttonCancel.setOnClickListener(buttonCancelListener);}}


使用buttonCancel.setOnClickListener(buttonCancelListener); 抛出异常因为buttonCancel为null。我做错了什么?


喵喔喔
浏览 491回答 3
3回答

蓝山帝景

您的代码没有问题,正确的一切都应该正常工作。遇到null via findViewById()方法的最常见错误是当你忘记调用setContentView()或调用错误的布局时。我建议清理你的项目,然后再试一次!

慕森卡

我遇到了同样的麻烦,但是在清理完我的项目并再次运行它之后就完美了。

开满天机

我不是100%肯定,但你在类初始化中调用findviewbyid。我认为在onCreate方法之前调用此代码,因此无法找到视图。在oncreate方法中初始化侦听器应该可以工作。
随时随地看视频慕课网APP

相关分类

Android
我要回答