2014-11-06 65 views
0

我自定义了对话框布局中的复选框,您可以看到下面的代码。如何保存并获取自定义复选框值

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingBottom="15dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" 
    android:paddingTop="10dp"> 

    <CheckBox 
     android:id="@+id/remember_choice" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="10dp" 
     android:layout_marginBottom="10dp" 
     android:button="@drawable/checkbox_btn_holo_light" 
     android:onClick="onCheckboxClicked" 
     android:text="@string/remember_my_choice" /> 

</LinearLayout> 

这会给checkbox一个checkbox_btn_holo_light样式。但问题是复选框无法保存并保留其isChecked()值。

为了捕捉点击事件,我在xml中添加onclick标记,并根据official document添加onCheckboxClicked方法。请参阅下面的onCheckboxClicked方法。

public void onCheckboxClicked(View view) { 
    isRememberChoiceChecked = ((CheckBox) view).isChecked(); 
} 

更糟的是当我运行该项目,点击复选框,应用程序崩溃。 logcat中的错误显示如下。

java.lang.IllegalStateException: Could not find a method onCheckboxClicked(View) in the activity class com.seafile.seadroid2.AccountDetailActivity for onClick handler on view class android.widget.CheckBox with id 'remember_choice' 

我想知道为什么会发生这种情况。

  • 所以是有可能的自定义复选框布局上对话框布局?
  • 如果可以自定义复选框(设置自定义背景),那么如何获取其检查状态?

我对此很困惑。任何建议将被认真考虑。

+0

你必须实现OnCheckedChangeListener()。 – 2014-11-06 10:24:36

+0

感谢您的回复,但也不\'吨工作的评论 – 2014-11-07 02:39:10

回答

0

删除此行从您的XML

 android:onClick="onCheckboxClicked" 

,并在你的代码,例如onCreate方法做

 CheckBox chx = (CheckBox) view.findViewById(R.id.remember_choice); 

,然后你可以这样做:

   chx.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

        @Override 
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
         // here you have your ischecked value do your job 
         // this will fire every time checbox is clicked 
        } 
       }); 
+0

谢谢,但' chx.setOnCheckedChangeListener()'根本不能捕获onCheckedChanged事件。请注意,我在这里使用自定义复选框,所以它不能以常用的方式工作 – 2014-11-07 02:46:46

0

按钮checkboxbtn; CheckBox none;

none =(CheckBox)rootView.findViewById(R.id.chknone);

checkboxbtn.setOnClickListener(新View.OnClickListener(){

 public void onClick(View v) { 
      // TODO Auto-generated method stub 

      if ((none.isChecked() == true)) { 
       // String strnone = null; 
       strnone = "none"; 
       Log.e("none", strnone); 
      } 

    });