Android 是否选中切换按钮

Android 是否选中切换按钮,android,togglebutton,Android,Togglebutton,我试着看看复选框是否被选中,但我得到了错误 定义复选框代码: public class Preferences extends PreferenceActivity { CheckBoxPreference togglePref; ... } 复选框代码: public void checkNotify() { if (togglePref.isChecked()==(true)) { ... } } OnCreate代码: protected void onCre

我试着看看复选框是否被选中,但我得到了错误

定义复选框代码:

public class Preferences extends PreferenceActivity {

CheckBoxPreference togglePref;

...
}
复选框代码:

public void checkNotify() {   

if (togglePref.isChecked()==(true)) {

...

   }

}
OnCreate代码:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //SharedPreferences settings = getSharedPreferences("EasySettingsPreferences", MODE_PRIVATE);
    //boolean notify = settings.getBoolean("notify", false);

    checkNotify();
    rootView = new LinearLayout(this);
    rootView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    rootView.setOrientation(LinearLayout.VERTICAL);

    togglePref =  new CheckBoxPreference(this);

    textView = new TextView(this);
    textView.setText(R.string.app_name);

    titleView = new LinearLayout(this);
    titleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 26));
    titleView.setBackgroundResource(R.drawable.pattern_carbon_fiber_dark);

    titleView.addView(textView);
    preferenceView = new ListView(this);
    preferenceView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    preferenceView.setId(android.R.id.list);
    PreferenceScreen screen = createPreferenceHierarchy();
    screen.bind(preferenceView);
    preferenceView.setAdapter(screen.getRootAdapter());

    rootView.addView(titleView);
    rootView.addView(preferenceView);

    this.setContentView(rootView);
    setPreferenceScreen(screen);
}

Logcat图片:

调试器图片


如果可以的话,请帮助我。谢谢

我想你从来没有初始化过
togglePref
。为了确保我们需要查看
onCreate()
。(如果我猜错了,我会更新我的答案…)

编辑 我是对的。在初始化
togglePref
变量之前调用
checkNotify()
。检查您的逻辑,如果在调用其他方法之前调用该方法真的有意义,或者如果您稍后调用它,则可以

提示:您可以简化if语句:

// yours:
if (togglePref.isChecked()==(true)) {
// simplified:
if (togglePref.isChecked()) {

onCreate()
方法中,在初始化
togglePref
之前调用
checkNotify()
。您希望将该初始化向上移动(或向下移动
checkNotify()

下次不需要从logcat输出创建图片时,我添加了调试程序的图片。只需复制并粘贴到此处:)