android-fragments 将自订布景主题套用至PreferenceFragment

2fjabf4q  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(133)

我有一个多窗格视图,有左右两个片段。在右边的片段上,我正在启动一个PreferenceFragment。问题是片段看起来完全扭曲,没有任何样式。有没有办法只对PreferenceFragment应用主题?
我尝试了this,但没有成功
我的代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // create ContextThemeWrapper from the original Activity Context with the custom theme
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppTheme_PreferenceTheme);

    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

    View view = super.onCreateView(localInflater, container, savedInstanceState);

    return view;

}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState); 

    addPreferencesFromResource(R.xml.app_settings_preference_layout);
}

我认为这个解决方案不起作用,因为我已经在onCreate中膨胀了preference-layout。有没有一种方法可以不使用addPreferencesFromResource方法而只使用LayoutInflater服务来膨胀preference-layout?

a2mppw5e

a2mppw5e1#

我用这个来设置PreferenceFragments的样式:

<style name="PreferenceTheme" parent="@style/AppTheme">
    <item name="android:textColor">@color/colorPrimary</item>
    <item name="android:background">@color/cpWhite</item>
    ...
</style>

然后,在onCreateView中:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ...
    container.getContext().setTheme(R.style.PreferenceTheme);
}

对我有帮助。希望对你也有帮助。

ih99xse1

ih99xse12#

在2022中,如果您使用PreferenceFragmentCompat创建首选项屏幕,您可以在其源代码中找到从R.attr.preferenceTheme获取主题的尝试。因此,如果您在应用主题中将此值设置为所需的主题,则将应用所需的主题。

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    ...
    <item name="preferenceTheme">@style/SettingsTheme</item>
    ...
</style>

<style name="SettingsTheme" parent="@style/PreferenceThemeOverlay">
    <item name="preferenceCategoryTitleTextColor">?attr/colorPrimary</item>
</style>

对我来说非常有效

相关问题