有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java复选框。setOnCheckedChangeListener调用崩溃应用程序?

我有这个简单的代码,但我不明白为什么它会使应用程序崩溃

package com.leonnears.安卓.andAnother;

import 安卓.app.Activity;
import 安卓.os.Bundle;
import 安卓.widget.CheckBox;
import 安卓.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);

看看坠机事件是否是出于某种原因而发生的,看起来是的

有人能帮我吗?我将不胜感激


共 (1) 个答案

  1. # 1 楼答案

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

    将语句重新排列为

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

    您必须先设置视图,然后使用其资源