简体   繁体   English

如何更改放置在PreferenceFragment中的首选项的摘要

[英]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. 我正在开发应用程序,并试图遵循Android准则并使用android studio模板。 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). 我在使用首选项活动时遇到了种种麻烦,特别是我无法在加载首选项的片段之外访问首选项,即我需要根据活动而不是片段修改首选项的摘要,因为尝试鉴于片段是静态类并且为摘要提供新值的方法是非静态的,因此无法修改片段内部(这是get版本方法,该方法使用getPackageManager非静态方法)。 Is there a way to acromplish this? 有没有办法夸大这一点?

You should be able to access the packageManager from within the fragment. 您应该能够从片段中访问packageManager。 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. 您还可以从片段中的Activity上调用方法,并向其传递您要更新摘要的优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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