Spo*_*ght 4 android android-preferences android-fragments android-support-library preferencefragment
我正在尝试使用新的Preference v14支持库.为了给首选项提供材质样式,我在Activity上使用以下样式:
<style name="PreferenceTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>
Run Code Online (Sandbox Code Playgroud)
这很好.我的问题是,当我在运行时添加新的首选项时,它们会使用旧主题进行膨胀.这是结果的屏幕截图:

如您所见,通过XML添加的第一个首选项具有新的Material样式,而其他首选项则没有.
您对如何解决问题有任何暗示吗?
编辑 这是我用来在运行时添加首选项的代码示例:
import android.support.v7.preference.ListPreference;
for (...) {
final ListPreference p = new ListPreference(getActivity());
p.setTitle(name);
p.setSummary(langname);
p.setEntryValues(langEntryValues);
p.setEntries(langDisplayValues);
p.setDialogTitle(R.string.select_language);
category.addPreference(p);
}
Run Code Online (Sandbox Code Playgroud)
PS:出现相同的行为 android.support.v7.preference.Preference
Ger*_*ssy 17
你所面临的问题Context与其主题有关并且如何运作.您的代码通过传递getActivity()给构造函数来检索上下文,但是,这不是您想要的上下文.以下是应用正确样式的解决方案:
final Context ctx = getPreferenceManager().getContext();
for (...) {
final ListPreference p = new ListPreference(ctx);
// [...]
category.addPreference(p);
}
Run Code Online (Sandbox Code Playgroud)
这PreferenceFragmentCompat是onCreate(...)方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TypedValue tv = new TypedValue();
this.getActivity().getTheme().resolveAttribute(attr.preferenceTheme, tv, true);
int theme = tv.resourceId;
if(theme <= 0) {
throw new IllegalStateException("Must specify preferenceTheme in theme");
} else {
this.mStyledContext = new ContextThemeWrapper(this.getActivity(), theme);
this.mPreferenceManager = new PreferenceManager(this.mStyledContext);
// [...]
this.onCreatePreferences(savedInstanceState, rootKey);
}
}
Run Code Online (Sandbox Code Playgroud)
重要的路线:
this.getActivity().getTheme().resolveAttribute(attr.preferenceTheme, tv, true);
int theme = tv.resourceId;
Run Code Online (Sandbox Code Playgroud)
这里preferenceTheme是从Activity的主题中检索的.如果它存在(即theme不是0),PFC(PreferenceFragmentCompat)会创建一个新的主题包装器,它将包含样式信息:
this.mStyledContext = new ContextThemeWrapper(this.getActivity(), theme);
Run Code Online (Sandbox Code Playgroud)
使用这种样式化的上下文,PFC现在可以创建PreferenceManager:
this.mPreferenceManager = new PreferenceManager(this.mStyledContext);
Run Code Online (Sandbox Code Playgroud)
这个PFC的根样式现在preferenceTheme包含所有不同的子样式(preferenceStyle例如).
您的解决方案的问题是Preference该类preferenceStyle在构造函数传递的上下文中查找属性.但是,它只在您的preferenceTheme,而不是在Activity的主题中定义.
| 归档时间: |
|
| 查看次数: |
6535 次 |
| 最近记录: |