Github 例子 ps:提供狀態(tài)欄導(dǎo)航欄操作
例子
SystemUiHelper.get(activity)
.setStatusBarColor(0)
.setNavigationBarColor(0x33ffffff)
.setLightStatusBar()
.setLightNavigationBar()
.fullScreen()
.systemUiHeight(new SystemUiAttrCallback() {
@override
public void windowPaddingSize(int left, int top, int right, int bottom) {
}
});
前言
距離Android5.0誕生已經(jīng)很長(zhǎng)一段時(shí)間了,透明狀態(tài)欄也不再新鮮烤送,但是還是有很多人不知道如何獲取狀態(tài)欄的高度進(jìn)行適配屏幕寒随,所以寫(xiě)一篇文章普及下。(國(guó)內(nèi)稱(chēng)之為沉浸式狀態(tài)欄,這個(gè)說(shuō)法是錯(cuò)的)
正文
相信大多人都知道妻往,狀態(tài)欄的高度是通過(guò)Padding進(jìn)行設(shè)置的互艾,這篇文章主要就是介紹如何獲取這個(gè)Padding的高度。
所有View的展示都離不開(kāi)WindowInsets類(lèi)讯泣,沒(méi)錯(cuò)纫普,就是這個(gè)類(lèi)記錄了狀態(tài)欄的高度,只要獲取到DecorView的WindowInsets好渠,我們就能獲取到狀態(tài)欄的高度
/**
* Describes a set of insets for window content.
*
* <p>WindowInsets are immutable and may be expanded to include more inset types in the future.
* To adjust insets, use one of the supplied clone methods to obtain a new WindowInsets instance
* with the adjusted properties.</p>
*
* @see View.OnApplyWindowInsetsListener
* @see View#onApplyWindowInsets(WindowInsets)
*/
public final class WindowInsets {
***
}
我們可以通過(guò)獲取DecorView通過(guò)設(shè)置監(jiān)聽(tīng)來(lái)獲取WindowInsets
{
getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
insets.getSystemWindowInsetTop();//這就是狀態(tài)欄高度
//獲取高度后的處理
return v.onApplyWindowInsets(insets);//此函數(shù)必須調(diào)用局嘁,否則WindowInsets無(wú)效
}
});
}
監(jiān)聽(tīng)返回需調(diào)用onApplyWindowInsets函數(shù),通過(guò)源碼可以看到晦墙,不設(shè)置監(jiān)聽(tīng)時(shí)是調(diào)用了onApplyWindowInsets函數(shù)的悦昵,設(shè)置監(jiān)聽(tīng)后就沒(méi)有調(diào)用了,不調(diào)用該函數(shù)會(huì)使得WindowInsets無(wú)法正確配置
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
try {
mPrivateFlags3 |= PFLAG3_APPLYING_INSETS;
if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {
return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);
} else {
return onApplyWindowInsets(insets);
}
} finally {
mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS;
}
}