0

我想使用预定义的共享首选项来设置 checkBoxPreference 的值,并使用 checkBoxPreference 设置共享首选项。我试过这段代码,但即使我知道“pre_definied_shared_prefs”存在,checkboxPref 总是最终为空。

final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("pre_defined_shared_prefs");


    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Boolean b = (Boolean) newValue;

            Intent i = getIntent();
            Integer show_num = i.getIntExtra("show_num", -1);
            SettingsManager s = new SettingsManager();
            s.setShowNotification(show_num, b, getApplicationContext());

            return true;
        }
    });

为什么会这样,我该如何解决?

4

1 回答 1

0

我的preference.xml:

<CheckBoxPreference
          android:title="Show Call UI"
          android:defaultValue="true"
          android:summary="Show Call Interface when clicking call button"
          android:key="checkboxPref" />

休息代码:

final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());       
            return true;
        }
    }); 

这是有关如何创建新复选框首选项并将其添加到您希望的组的示例或查看

public class MyPreferenceActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_preference_activity);

        //fetch the item where you wish to insert the CheckBoxPreference, in this case a PreferenceCategory with key "targetCategory"
        PreferenceCategory targetCategory = (PreferenceCategory)findPreference("targetCategory");

        //create one check box for each setting you need
        CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
        //make sure each key is unique  
        checkBoxPreference.setKey("keyName");
        checkBoxPreference.setChecked(true);

        targetCategory.addPreference(checkBoxPreference);
    }
}
于 2013-01-20T04:25:53.287 回答