Android沉浸式状态栏实现(半透明浮动状态栏)Activity全屏显示

看到好多人对“沉浸式”这个词的释义,学到了点,不过这里我只是关注通知栏是否透明,且不影响我APP UI的布局即可。

先来看对比图:
默认的造型:

沉浸式处理后的造型:


实现步骤如下:

Step1. 下载SystemBarTint开源库,拷贝或引入其中的SystemBarTintManager.java至本项目中

Step2.在项目res目录下新建values-v19文件夹,新建style.xml文件,内容为:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme for API 19+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v19/styles.xml on API 19+ devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.NoActionBar">

        <!-- API 19 theme customizations can go here. -->
        <item name="android:windowContentOverlay">@null</item>
    </style>

</resources>

此处,确认manifest文件中application的android:theme="AppBaseTheme"或继承自“AppBaseTheme”。以保证在Android4.4以上该样式生效。

Step3. 在需要体现沉浸式效果的页面Activity中添加以下代码:
protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.main_bg_blue);// 通知栏所需颜色
		}
	}


(此时一般会发现APP的整个界面充满了屏幕,UI顶部的部分原色被通知栏遮盖了一点,透明或半透明),效果如下。


Step4. 实现UI顶部的自适应,从通知栏下方开始显示。
在界面根布局文件中添加
android:fitsSystemWindows="true"
属性,让界面布局适应系统屏幕空间(给状态栏让出位子)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/white"
    android:orientation="vertical" >
    ...
</LinearLayout>

最终效果如对比图所示。

后记
      其实不用SystemBarTintManager 库也可以实现上述效果,不过需要对界面布局的背景色做特定设置(根布局需要与状态栏背景色一致),这样工作量有点大,而SystemBarTintManager类可以灵活的设置背景色。(其变更不会影响界面其他元素的背景色)。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值