我有以下两个主题:
<!-- Base application theme. -->
<style name="Theme.MyDemoApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/purple_500</item>
</style>
<!-- Base application theme with a prominent app bar incl. image -->
<style name="Theme.MyDemoApp.Prominent.Image" parent="Theme.MyDemoApp">
<!-- Transparent status bar, so that the image extents to the status bar-->
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
主题Theme.MyDemoApp
正在我的应用程序或实际上我的整个应用程序中使用.
一个活动打开一个特殊的片段.这个片段使用了一个带有图像的突出应用程序栏,图像也显示在状态栏上.
因此,我创建了一个名为Theme.MyDemoApp.Prominent.Image
的主题,它使我能够在状态栏上显示图像.
由于片段将从不同的活动和片段中调用,因此我希望将Theme.MyDemoApp.Prominent.Image
设置为片段.
我已经寻找了许多将主题设置为碎片的解决方案,例如:
1)
@Override
public void onAttach(@NonNull Context context) {
context.setTheme(R.style.Theme_MyDemoApp_Prominent_Image);
super.onAttach(context);
}
@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.Theme_MyDemoApp_Prominent_Image);
//clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
return inflater.inflate(R.layout.fragment_demo_appbar_image, container, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getContext().getTheme().applyStyle(R.style.Theme_MyDemoApp_Prominent_Image, true);
return inflater.inflate(R.layout.fragment_demo_appbar_image, container, false);
}
直接在片段XML文件中设置主题
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/Theme.MyDemoApp.Prominent.Image"
android:theme="@style/Theme.MyDemoApp.Prominent.Image"
>
<!-- bla bla bla bla -->
</androidx.coordinatorlayout.widget.CoordinatorLayout>
然而,上面try 过的解决方案对我来说都不起作用.主题不会改变,也就是状态栏不透明. 如果我把片断主题参数放到活动主题中,它的工作就像一个护身符,但这不是我计划做的……
问题可能是什么,以及我如何才能正确设置片段中的主题?