英文:
Change color of status bar in particular fragment
问题
在我的Android应用程序中,有一个MainActivity和许多片段。
在HomeFragment中,我需要有一个紫色的状态栏,但在其他片段中是白色的。
应用程序使用以下样式:
<style name="AppStyle" parent="Theme.MaterialComponents.Light.NoActionBar">
对于MainActivity,我使用以下样式:
<style name="Theme.ActivityStatusBarPurple" parent="AppStyle">
<item name="android:statusBarColor">@color/color_purple</item>
</style>
在HomeFragment的onCreateView
中,我使用以下代码:
requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
在HomeFragment的onDestroyView
中,我使用以下代码:
requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
部分地,我获得了期望的结果:状态栏具有紫色,但有两个副作用:
我的布局重叠在底部的导航栏上,并且其他片段的状态栏中可见紫色。
如何只重叠状态栏而不更改导航栏,以及如何保持其他片段的状态栏为白色?
英文:
In my android app there is one MainActivity and a lot of fragments.
In HomeFragment I need to have a status bar with color purple but in other white.
App has
style name="AppStyle" parent="Theme.MaterialComponents.Light.NoActionBar"
For MainActivity I use
<style name="Theme.ActivityStatusBarPurple" parent="AppStyle">
<item name="android:statusBarColor">@color/color_purple</item>
</style>
In onCreateView
of HomeFragment I use
requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
In onDestroyView
of HomeFragment I use
requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
Partially I've got desirable result: status bar has purple color but there two side effects:
my layout overlap navigation bar at bottom and a purple color is visible in other fragments status bar.
How to overlap only status bar not changing a navigation bar and how to keep white color for other fragments status bars?
答案1
得分: 1
我找到了一个非常简单的解决方案。在每个片段的onCreateView
中,我设置了这一行:
requireActivity().window.statusBarColor = ContextCompat.getColor(requireActivity(), R.color.my_color)
无需更改主题
英文:
I found a very simple solution. In every fragment's onCreateView
I set this line:
requireActivity().window.statusBarColor = ContextCompat.getColor(requireActivity(), R.color.my_color)
No need to change a theme
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论