为Fragment指定样式

2021-10-19  本文已影响0人  100个大西瓜

在对Activity指定样式,可以通过清单文件中指定样式,

   <activity
            android:name=".SettingsActivity"
            android:theme="@style/SettingStyle"
            android:screenOrientation="landscape" />

Fragment可以通过下面这种方式来实现
当Fragment与Activity或者App的整个主题不相符时,如整个App的字体大小是16sp,但是这个Fragment的字体都要求是14sp时。
可以继承原来的主题,然后在onCreateView中设置,如下:
原来的样式:

    <!-- Base application theme. -->
    <style name="Theme.AppTheme" parent="BaseTheme.MyTheme">
        <!-- Customize your theme here. -->
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:textSize">16sp</item>
    </style>

自定义的Fragment样式:

    <!-- add for Fragment -->
    <style name="Theme.AppTheme.MyFragment">
        <item name="android:textSize">14sp</item>
    </style>

在Fragment中使用:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final ContextThemeWrapper wrapper = new ContextThemeWrapper(requireActivity(),
                R.style.Theme_AppTheme_MyFragment);
        final LayoutInflater cloneInContext = inflater.cloneInContext(wrapper);
        return cloneInContext.inflate(R.layout.fragment_main_frame, container, false);
    }

加载样式:

final ContextThemeWrapper wrapper = new ContextThemeWrapper(requireActivity(),R.style.Theme_AppTheme_MyFragment);

对LayoutInflater设置新的主题/样式:

final LayoutInflater cloneInContext = inflater.cloneInContext(wrapper);

使用新的打气筒加载布局:

return cloneInContext.inflate(R.layout.fragment_main_frame, container, false);
上一篇 下一篇

猜你喜欢

热点阅读