Jeevan
Jeevan

Reputation: 8772

Apply custom theme to PreferenceFragment

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?

Upvotes: 8

Views: 3125

Answers (2)

Andriy Koretskyy
Andriy Koretskyy

Reputation: 575

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

Upvotes: 0

Harsh Modani
Harsh Modani

Reputation: 221

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.

Upvotes: 2

Related Questions