2014-11-06 68 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); 
      } 

    });