1

我有这个简单的代码,但我一生都无法弄清楚为什么它会导致应用程序崩溃。

package com.leonnears.android.andAnother;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class AndAnotherActivity extends Activity
{
    CheckBox dahBox;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        dahBox = (CheckBox)findViewById(R.id.someCheck);
        setContentView(R.layout.main);
        dahBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {   
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    dahBox.setText("This checkbox is: checked");
                }else
                {
                    dahBox.setText("This checkbox is: unchecked");
                }
            }
        });
    }
}

我已经完成了测试并注释了部分代码,看起来调用使dahBox.setOnCheckedChangeListener()我的程序崩溃了。在某一时刻,我最终这样做了:

dahBox.setOnCheckedChangeListener(null);

要查看崩溃是否可能由于某种原因而存在,而且看起来确实如此。

有人可以帮我弄这个吗?我将不胜感激。

4

1 回答 1

2
dahBox = (CheckBox)findViewById(R.id.someCheck);
        setContentView(R.layout.main);

将语句重新排列为

setContentView(R.layout.main);
    dahBox = (CheckBox)findViewById(R.id.someCheck);

你必须先设置视图然后使用它的资源

于 2011-12-24T04:55:14.030 回答