CheckBox PreferenceScreen

时间:2012-02-23 12:34:28

标签: android checkbox preferences

我正在使用此xml代码执行preferenceScreen:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:orderingFromXml="true">
<PreferenceCategory 
       android:key="pref1" 
       android:title="Search All">
    <CheckBoxPreference 
          android:key="check_all" 
          android:title="Check"/>
</PreferenceCategory>
<PreferenceCategory 
       android:title="Specific Search" 
       android:key="pref2">
    <ListPreference 
          android:title="Food" 
          android:key="opcion1"
          android:dialogTitle="Escoge Categoria"
          android:entryValues="@array/codigoCateg" 
          android:entries="@array/categorias" 
          android:negativeButtonText="Cancel"/>
    <ListPreference android:title="Dificultad"/>
    <ListPreference android:title="Otras"/>
</PreferenceCategory>

Java代码:

public class OpcionesBusqueda extends PreferenceActivity {

boolean CheckBoxPreference;
private PreferenceCategory Pref2;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.video_search);

    Pref2=(PreferenceCategory)findPreference("pref2");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    CheckBoxPreference = prefs.getBoolean("check_all", true);

    if(CheckBoxPreference==true){
        Pref2.setEnabled(false);
    }
    else{
        Pref2.setEnabled(true);
    }
}

}

我想要做的是如果选中复选框,则应禁用pref2(preferencecategory2),如果未选中,则应启用它。有些事情我做错了,或者可能不止一个。

感谢。


我按照亚历克斯的回答进行了一些更改,我到达了欲望代码,这里是更正的代码:

public class OpcionesBusqueda extends PreferenceActivity {

private CheckBoxPreference Check;
private PreferenceCategory Pref2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.video_search);

    Check=(CheckBoxPreference)findPreference("check_all");
    Pref2=(PreferenceCategory)findPreference("pref2");

    Check.setOnPreferenceChangeListener(new CheckBoxPreference.OnPreferenceChangeListener() {
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
                Pref2.setEnabled((Boolean)newValue == false);
                return true;
        }
    });        

}

1 个答案:

答案 0 :(得分:2)

您可能需要为OnPreferenceChangeListener偏好设置check_all,并更改pref2

onPreferenceChaged内的OnPreferenceChangeListener
CheckBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
     boolean onPreferenceChange(Preference preference, Object newValue) {
          Pref2.setEnabled((Boolean)newValue == false); 
     }
}