android getwindow 在fragment不能使用,Android Fragment 布局使用 fitsSystemWindows = true 无效解决方案...
最近遇到一個奇葩問題,導航欄多個Fragment沉浸,fitsSystemWindows = true只在一個Fragment有效,其他Fragment都是無效的(即:toolbar和狀態欄重疊)
這種問題產生的原因:當第一個Fragment添加到Activity中的時候,Activity尋找出有fitsSystemWindows的子布局為其預留出狀態欄的空間,其實就是設置一個padding,而其他Fragment添加到Activity中的時候,因為狀態欄空間的適配已經被消費過一次了,Activity并不會再次去添加這個padding。因此我們需要自定義一個FrameLayout,重寫它的狀態欄空間適配的時機和它的適配事件的分發。
經過一系列翻查,測試,最終找到了一種合適的處理方案,廢話不多說一起來看一下吧!
public class WindowInsetsFrameLayout extends FrameLayout {
public WindowInsetsFrameLayout(Context context) {
this(context, null);
}
public WindowInsetsFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
requestApplyInsets();
}
@Override
public void onChildViewRemoved(View parent, View child) {
}
});
}
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
int childCount = getChildCount();
for (int index = 0; index < childCount; index++)
getChildAt(index).dispatchApplyWindowInsets(insets);
return insets;
}
}
因為Fragment是添加到FrameLayout這個容器的,我們給他設置一個布局層次結構改變的監聽,當Fragment被添加進去的時候,通過requestApplyInsets()方法使Activity重新進行一次狀態欄空間的適配,因為FrameLayout中還有其他的Fragment,我們還需要重寫onApplyWindowInsets方法,對其子View進行遍歷,逐個分發狀態欄空間的適配事件。
總結
以上是生活随笔為你收集整理的android getwindow 在fragment不能使用,Android Fragment 布局使用 fitsSystemWindows = true 无效解决方案...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (笔记)Mysql命令drop data
- 下一篇: Linux中断(interrupt)子系