简体   繁体   中英

How to change the summary of a preference placed in a PreferenceFragment

I'm developing an app and I'm trying to follow Android guidelines and to use android studio templates. I'm having various troubles with preference activity and in particular I can't get access to a preference outside the fragment in which it's loaded, ie I need to modify the summary of a preference from the activity and not from the fragment, because trying to modify if inside the fragment is impossible given that it's a static class and the method which provides the new value for the summary is non-static (it's a get version method, which uses the getPackageManager non-static method). Is there a way to acromplish this?

You should be able to access the packageManager from within the fragment. For example:

version = getActivity().getPackageManager().
                getPackageInfo(getActivity().getPackageName(),  0).versionName;

And if you want to do it from the activity, you just need to get a reference to the preference.

First get a reference to the preference within the fragment:

Preference myPref;    

public void onCreate(){
    myPref = findPreference("myPref");
}

public Preference getMyPref(){
    return myPref;
}

And in the activity you can do:

myFragment.getMyPref().setSummary("Preference Summary");

You can also call a method on the Activity from the fragment and pass it the preference that you want to update the summary on.

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