demand
MainActivity contains five fragments, but only the HomeFragment is required to be immersive. The rest of the fragments are not immersive and remain the same
Note: only supported by Android21 and above
Train of thought
Premise: Immersion only works on activities!
Idea 1
Thinking steps
- Make MainAcitivity immersive, and all Fragment pages will be immersive;
- Add a View for each Fragment page, pay attention to the layout (FrameLayout layout may be difficult to handle);
- Implement new View height and background color for each Fragment.
Implementation steps
1. Make MainAcitivity immersive:
StatusBarUtil.setStatusBarTransparent(activity);
Copy the code
Create a View for every Fragment page that does not need to be immersive:
<View
android:id="@+id/view_status_bar"
android:layout_width="match_parent"
android:layout_height="0dp"/>
Copy the code
Add new View height and background color for every Fragment that does not need to implement immersion:
StatusBarUtil.setStatusViewAttr(view, activity);
Copy the code
The advantages and disadvantages
- Advantages: high controllability; And the height and background color are statically implemented in the layout file, without the need for real-time calculation (as opposed to idea 2).
- Cons: You need to add redundant and similar code to every Fragment page that doesn’t want to be immersive.
Idea 2
Thinking steps
- Make MainAcitivity immersive, and all Fragment pages will be immersive;
- Once you get the DecorView, set the child View dynamically
topMargin
, realizing immersion during Fragment page switching
Implementation steps
1. Make MainAcitivity immersive:
StatusBarUtil.setStatusBarTransparent(activity);
Copy the code
2, make the first Fragment page displayed by default immersive:
StatusBarUtil.createStatusView(activity);
StatusBarUtil.hideStatusView(activity, true);
Copy the code
3. Add the following code to a Fragment that does not implement immersion:
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
StatusBarUtil.hideStatusView(activity, false);
} else {
StatusBarUtil.hideStatusView(activity, true); }}Copy the code
The advantages and disadvantages
- Advantages: Can be integrated into a tool class, no need to add new code in the Fragment.
- Cons: Need variety
topMargin
Causes the page to slide slightly.
Idea 3
Still searching……
The source code
StatusBar