How to get a preference value in preference fragment

自古美人都是妖i 提交于 2020-01-02 04:39:10

问题


I want to show the value of preferences in a custom preference screen. For this I need to get the values, in this case strings, within the preference fragment. In non fragments (activities) I get the values with e.g. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); and get the string with String phonenumber = prefs.getString("preference_name", null); but in the preference fragment getDefaultSharedPreferences is not applicable for preference fragment.

Any idea how to solve this?

Here's my code snippet:

public class PreferencesFragment extends PreferenceFragment implements
    OnSharedPreferenceChangeListener {

TextView tvusername, tvphonenumber;     

@Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     addPreferencesFromResource(R.xml.preferences);
     getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);

     final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);


    // entering preference phonenumber in text view
            String phonenumber = prefs.getString("phonenumber", null);
            ;
            tvphonenumber.setText(phonenumber);

    // entering preference username in text view
            String username = prefs.getString("username", null);
            ;
            tvusername.setText(username);

}

回答1:


In onActivityCreated (It's the time when the activity is created) of your fragment class, you do

Context hostActivity = getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(hostActivity);

That's how you access the hostActivity from the attached fragment.



来源:https://stackoverflow.com/questions/25532189/how-to-get-a-preference-value-in-preference-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!