在特定片段中更改状态栏的颜色。

huangapple go评论49阅读模式
英文:

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=&quot;AppStyle&quot; parent=&quot;Theme.MaterialComponents.Light.NoActionBar&quot;

For MainActivity I use

&lt;style name=&quot;Theme.ActivityStatusBarPurple&quot; parent=&quot;AppStyle&quot;&gt;
    &lt;item name=&quot;android:statusBarColor&quot;&gt;@color/color_purple&lt;/item&gt;
&lt;/style&gt;

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

huangapple
  • 本文由 发表于 2023年6月14日 23:48:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定