1、在style.xml中定义toolbar的颜色
[html] view plain copy
- <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、布局文件添加属性
[plain] view plain copy
- android:fitsSystemWindows="true"
- android:clipToPadding="true"
3、在Activity的onCreate(Bundle savedInstanceState)方法中添加代码
[java] view plain copy
- @Override
- protected 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);
- }