Apply custom theme in PreferenceFragment

I have a multi-pane view with left and right snippet. On the right fragment, run the PreferenceFragment. The problem is that the fragment looks completely distorted without any style. Is there a way to apply a theme only to a PreferenceFragment element?

I tried this one but it didn't 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 had already inflated the preference setting in onCreate. Is there a way to inflate the preferences layout without using the addPreferencesFromResource method and just using the LayoutInflater service?

+7
android android-fragments android-preferences
source share
1 answer

you don't need to use onCreateView ()

You can:

1) define the application layout and fragments in your xml activity, for example:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ..blabla <LinearLayout <fragment android:layout_width="match_parent" android:layout_height="wrap_content" android:name="com.xxx.MyPreferencesFragment1" //your own extended class android:id="@+id/preference_fragment1"/> <fragment android:name="com.xxx.MyPreferencesFragment2" //your own extended class android:id="@+id/preference_fragment2"/> </LinearLayout> </RelativeLayout> 

from

 public class MyPreferencesFragment1 extends PreferenceFragment { // Required empty public constructor @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences1); 

OR you can:

2) only the linker / container ("R.id.fragments_layout") is defined in the xml operation, and the rest are from java code

 <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/fragments_layout"> // only layout - dont define fragments this case 

and cc now you also need to inflate the XML preferences file inside this layout container

 getFragmentManager().beginTransaction().replace/add(R.id.fragments_layout, new MyPreferencesFragment1()).commit(); getFragmentManager().beginTransaction().replace/add(R.id.fragments_layout, new MyPreferencesFragment2()).commit(); 
-2
source share

All Articles