Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
Jeevan Avatar asked Jan 30 '14 17:01

Jeevan


1 Answers

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.

like image 122
Harsh Modani Avatar answered Oct 30 '22 06:10

Harsh Modani