简体   繁体   中英

Android preferences how to work with switch statement

I have some preferences in my preference screen:

<PreferenceCategory
    android:key="category"
    android:summary="Category"
    android:title="Category">

    <Preference
        android:key="pref1"
        android:summary="desc"
        android:title="Pref 1" />

    <Preference
        android:key="pref2"
        android:summary="desc"
        android:title="Pref 2" />

</PreferenceCategory>

Finding them in PreferenceActivity :

Preference pref1, pref2;

@Override
    protected void onCreate(final Bundle savedInstanceState) {
      pref1 = findPreference("pref1");
      pref2 = findPreference("pref2");
}

And set some OnPreferenceClickListener to them. How do I correctly define which preference was clicked? I'd like to do it in case-switch style, but I cannot figure out which types should I use:

Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        switch (???){       //I guess, here goes the "preference"?
            case ???:       //getting error with pref1 or pref2

        }
        return false;
    }
}

If I put preference from onPreferenceClick in switch() , I will get errors with case .

You can get the corresponding preference like

@Override
public boolean onPreferenceClick (Preference preference)
{
    String key = preference.getKey();
    // do what ever you want with this key
}

ref: Preference Activity on Preference Click Listener

hope this helps :)

You can use the field key of Preference

public boolean onPreferenceClick(Preference preference) {
    if (preference.getKey().equals("pref1")) {
        ... do something ...
    } else if (preference.getKey().equals("pref2")) {
        ... do something ...
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM