【问题标题】:If a toggle button is checked or not是否选中了切换按钮
【发布时间】:2011-09-07 11:04:01
【问题描述】:

好吧,我正在尝试查看是否选中了一个复选框,但我得到了错误。

定义复选框代码:

public class Preferences extends PreferenceActivity {

CheckBoxPreference togglePref;

...
}

复选框代码:

public void checkNotify() {   

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

...

   }

}

创建代码:

 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 图片:

logcat pic http://img710.imageshack.us/img710/8529/unledxq.png

调试器图片

debugger pic http://img847.imageshack.us/img847/1192/unled1rn.png

如果可以,请帮助我。谢谢!

【问题讨论】:

  • 我添加了调试器的图片
  • 下次不需要从 logcat 输出创建图片。只需复制并粘贴到这里 :)

标签: android togglebutton


【解决方案1】:

我猜你从来没有初始化togglePref。可以肯定的是,我们需要查看onCreate()。 (如果我猜错了,我会更新我的答案...)

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

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

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

【讨论】:

    【解决方案2】:

    在您的onCreate() 方法中,您在togglePref 初始化之前调用了checkNotify()。您想上移初始化(或下移checkNotify()。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-17
      • 2016-09-26
      • 2012-02-16
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多