6

我正在尝试创建一个应用程序,其中首选项摘要根据CheckBoxPreference.

我不太确定如何查询首选项,因为好旧的isChecked()不起作用。

4

2 回答 2

17

Would be much simpler if you just used android:summaryOff and android:summaryOn in your preference layout. No code required. E.g:

<CheckBoxPreference
        android:enabled="true"
        android:key="alerts"
        android:title="Alerts" 

        android:summaryOn="You will get notified when something interesting happens"
        android:summaryOff="You will not be notified"
        /> 

See: http://developer.android.com/reference/android/preference/CheckBoxPreference.html

于 2013-09-25T07:11:58.767 回答
2
public class Preferences extends PreferenceActivity
        implements OnSharedPreferenceChangeListener {

    public final static String KEY_CHECK = "check";
    private CheckBoxPreference mCheckBoxPreference;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        addPreferencesFromResource(R.xml.preferences);
        mCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(KEY_CHECK);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        if (key.equals(KEY_CHECK)) {
            if (mCheckPreference.isChecked()) {
                mCheckPreference.setSummary(mCheckPreference.getEntry());
            }
        }
    }
}
于 2012-07-31T12:57:47.037 回答