【Android UI】状态栏和toolbar颜色一致

来源:互联网 发布:自制手机壁纸软件 编辑:程序博客网 时间:2024/06/11 02:40

1、在style.xml中定义toolbar的颜色

<resources>    <!-- Base application theme. -->    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">        <!-- Customize your theme here. -->        <!-- toolbar(actionbar)颜色 -->        <item name="colorPrimary">#4876FF</item>        <item name="android:windowTranslucentStatus">true</item>    </style>    <style name="AppTheme" parent="@style/AppBaseTheme"></style></resources>

2、布局文件添加属性

    android:fitsSystemWindows="true"    android:clipToPadding="true"

3、在Activity的onCreate(Bundle savedInstanceState)方法中添加代码

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {        Window window = getWindow();        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);        //获取样式中的属性值        TypedValue typedValue = new TypedValue();        this.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);        int[] attribute = new int[] { android.R.attr.colorPrimary };        TypedArray array = this.obtainStyledAttributes(typedValue.resourceId, attribute);        int color = array.getColor(0, Color.TRANSPARENT);        array.recycle();        window.setStatusBarColor(color);    }    setContentView(R.layout.activity_main);}

0 0