Android 沉浸式状态栏,状态栏颜色透明

来源:互联网 发布:罗斯福知乎 编辑:程序博客网 时间:2024/05/04 15:23

这一特性,需要在 Android 4.4 以上版本中才能使用。

第一种方法,通过XML配置:

首先在 styles.xml 文件中添加一个主题:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">        <item name="windowActionBar">false</item>        <item name="windowNoTitle">true</item>    </style>

然后在 AndroidManifest.xml 文件中配置

android:theme="@style/AppTheme"
添加在 application 标签中,则整个 app 都是沉浸式状态栏。

添加在 activity 标签中,则是在某个 activity 中应用沉浸式状态栏,其余 activity 不受影响。

第二种方法,在Java代码中配置:

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            //透明状态栏            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);            //透明导航栏            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);        }    }}
到这里已经是沉浸式状态栏了,但是在实际使用时会发现一个问题,状态栏不占空间了,界面最顶端内容会与状态栏重叠,如下

图:


所以这里还需要再做一些处理,在当前界面布局的最外层 layout 中添加

android:clipToPadding="true"android:fitsSystemWindows="true"
实际应用如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#ff8532"    android:clipToPadding="true"    android:fitsSystemWindows="true"    android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="liuwan1992"        android:textColor="#ffffff"        android:textSize="16sp" /></LinearLayout>
修改后效果如下:



上面的例子中是对 layout 设置的背景色,如果改成对 TextView 设置呢

很明显,又出问题了,状态栏并没有与 TextView 保持相同颜色,而是与 layout 一样默认成了白色背景。

那么,我们将要添加的两行代码加入 TextView 中看看效果

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#ff8532"        android:clipToPadding="true"        android:fitsSystemWindows="true"        android:text="liuwan1992"        android:textColor="#ffffff"        android:textSize="16sp" /></LinearLayout>

可以看到又达到了我们需要的效果,这里总结一下,我们在实际开发中,界面的背景颜色可能会另有设置,如果与界面背景保持一

致可能不是我们想要的效果,所以我们一般对界面布局中最顶端的一个控件做处理。

27 0
原创粉丝点击