距离上一篇
Android沉浸式状态栏(一)已经很久了,上一篇文章主要是讲原理以及如何实现的,在实际运用上面不是很方便。本篇文章引入框架和工具类来针对沉浸式状态栏进行处理。
布局代码如下所示:
AndroidStudio工程不做任何处理的情况下页面的布局图如下所示:
Android4.4沉浸式.png
Android5.0沉浸式.png
布局代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f00"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context="study.com.steepdemo2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>
上面布局代码中的
android:background=”#f00” 和
android:fitsSystemWindows=”true”是必须添加的属性,其中
android:background=”#f00”在使用工具类时代表的是状态栏的背景色。
一、工具类StatusBarUtil
AndroidStudio工程不做任何处理的情况下页面的布局图如下所示:
1.1 沉浸式状态栏
调用如下方法
StatusBarUtil.setStatusBarTranslucent(this, false, false, false);可以达到沉浸式状态栏的效果:
Android4.4沉浸式.png
Android5.0沉浸式.png
1.2 修改Android5.0版本以上状态栏字体颜色
在软件开发中经常会遇到UI图中状态栏的字体颜色为黑色,调用如下方法
StatusBarUtil.setStatusBarTranslucent(this, true, false, false);可以达到如下效果:
1.3 修改Android5.0版本以上状态栏为半透明
调用如下方法StatusBarUtil.setStatusBarTranslucent(this, false, true, false);可以达到如下效果:
1.4 修改Android5.0 版本以上底部导航栏为全透明
调用如下方法StatusBarUtil.setStatusBarTranslucent(this, false, false, true);可以达到如下效果:
二、框架SystemBarTint
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
/**
* 沉浸式状态栏第二版,用框架的方式来处理沉浸状态栏
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//方法一:
// StatusBarUtil.setStatusBarTranslucent(this, false, true, false);
//方法二:
method2();
}
private void method2() {
// 4.4及以上版本开启,5.0以上是半透明的
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
}
// create our manager instance after the content view is set
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
// enable navigation bar tint
tintManager.setNavigationBarTintEnabled(true);
// 自定义颜色
tintManager.setTintColor(Color.parseColor("#24b7a4"));
}
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
效果图如下所示:
本文介绍了一种在Android应用中实现沉浸式状态栏的方法,包括通过工具类和SystemBarTint框架调整状态栏的透明度、背景颜色及字体颜色等。
392

被折叠的 条评论
为什么被折叠?



