开发者

How do I refresh a specific Preference in Custom PreferenceActivity on Android?

开发者 https://www.devze.com 2023-03-28 03:48 出处:网络
First get your preference and then add/remove it. The key comes from your preference.xml file (or however you have named it)

First get your preference and then add/remove it.

The key comes from your preference.xml file (or however you have named it)

       <开发者_如何学Gocom.test.testing.PreferenceChangeColor
            android:key="color_preference"
            android:title="Line Color"
            android:summary="Change the color of your lines"
            android:defaultValue="-16555568" />

Then in your onCreate() method of your custom preference activity you do something like this:

     // Load the preferences from an XML resource
     addPreferencesFromResource(R.xml.game_preferences); 

     userColorPreference = (Preference)getPreferenceScreen().findPreference("color_preference");

Don't forget the private Preference var:

private Preference userColorPreference;

Now in your onSharedPreferenceChanged() method, you need to "hack" to get the preference to refresh.

  @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {        
        if (key.equals("color_preference")) {
            getPreferenceScreen().addPreference(userColorPreference);
            getPreferenceScreen().removePreference(userColorPreference);
        }
    }

This is the hack solution I came up with.

Anyone know the correct way to do this?

0

精彩评论

暂无评论...
验证码 换一张
取 消