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?

Community
  • 1
  • 1
Jeevan
  • 8,132
  • 12
  • 47
  • 65

1 Answers1

1

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.

Harsh Modani
  • 164
  • 8