Apply custom theme to PreferenceFragment
Asked Answered
R

2

8

I have multi-pane view with left and right fragment. On right fragment am launching a PreferenceFragment. Problem is the fragment looks completely distorted without any style. Is there a way to apply theme just to the PreferenceFragment alone ?

I tried this but it did not work

My code

    @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);
}

I think the solution did not work because I have already inflated preference-layout in onCreate. Is there a way to inflate preference-layout without using the method addPreferencesFromResource and just using LayoutInflater service?

Readymix answered 30/1, 2014 at 17:26 Comment(0)
G
2

I use this to set styles to PreferenceFragments:

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

And then, in the onCreateView:

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

Does the trick for me. I hope it helps you too.

Guajardo answered 28/11, 2020 at 16:6 Comment(0)
V
0

In 2022, if you use PreferenceFragmentCompat to create preference screen, you can find in it's source code an attempt to get theme from R.attr.preferenceTheme. So, if you set this value in your app theme to a desired theme, that desired them will be applied. Something like this:

<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>

Worked perfectly for me

Virulent answered 14/8, 2022 at 9:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.