我有左窗口和右边片段的多窗格视图。在右侧片段上启动PreferenceFragment。问题是片段看起来完全失真没有任何风格。有没有办法仅将主题应用于PreferenceFragment?
我试过了this,但它无效
我的代码
@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);
}
我认为解决方案不起作用,因为我已经在onCreate中夸大了首选项布局。有没有办法在不使用addPreferencesFromResource方法而只使用LayoutInflater服务的情况下对首选项布局进行膨胀?
答案 0 :(得分:0)
我使用它来将样式设置为PreferenceFragments:
<style name="PreferenceTheme" parent="@style/AppTheme">
<item name="android:textColor">@color/colorPrimary</item>
<item name="android:background">@color/cpWhite</item>
...
</style>
然后,在onCreateView中:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
...
container.getContext().setTheme(R.style.PreferenceTheme);
}
帮我个把戏。希望对您有帮助。
答案 1 :(得分:-3)
你不需要使用onCreateView()
你可以:1)在您的活动xml中定义您的应用程序布局和片段,例如:
<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>
与
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);
或你可以:
2)只在活动xml中定义一个占位符/容器布局(&#34; R.id.fragments_layout&#34;),并从java代码中完成剩下的工作
<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
和ofc现在你还需要在这个布局容器中扩充首选项xml文件
getFragmentManager().beginTransaction().replace/add(R.id.fragments_layout, new MyPreferencesFragment1()).commit();
getFragmentManager().beginTransaction().replace/add(R.id.fragments_layout, new MyPreferencesFragment2()).commit();