【Android UI】狀態欄和toolbar顏色一致

分類:IT技術 時間:2017-07-01

1、在style.xml中定義toolbar的顏色

 

[html] view plain copy

 print?

  1. <resources>  
  2.   
  3.     <!-- Base application theme. -->  
  4.     <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">  
  5.         <!-- Customize your theme here. -->  
  6.         <!-- toolbar(actionbar)顏色 -->  
  7.         <item name="colorPrimary">#4876FF</item>  
  8.         <item name="android:windowTranslucentStatus">true</item>  
  9.     </style>  
  10.   
  11.     <style name="AppTheme" parent="@style/AppBaseTheme"></style>  
  12.   
  13. </resources>  


2、布局文件添加屬性

 

 

[plain] view plain copy

 print?

  1. android:fitssystemWindows="true"  
  2. android:clipToPadding="true"  


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

 

 

[Java] view plain copy

 print?

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.   
  5.     if (Build.version.SDK_INT >= Build.VERSION_CODES.KITKAT) {  
  6.         Window window = getWindow();  
  7.         window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  
  8.                 | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
  9.         window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN  
  10.                 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  
  11.                 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);  
  12.         window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
  13.         //獲取樣式中的屬性值  
  14.         TypedValue typedValue = new TypedValue();  
  15.         this.getTheme().resolveAttribute(android.R.attr.colorPrimary, typedValue, true);  
  16.         int[] attribute = new int[] { android.R.attr.colorPrimary };  
  17.         TypedArray array = this.obtainStyledAttributes(typedValue.resourceId, attribute);  
  18.         int color = array.getColor(0, Color.TRANSPARENT);  
  19.         array.recycle();  
  20.   
  21.         window.setStatusBarColor(color);  
  22.     }  
  23.   
  24.     setContentView(R.layout.activity_main);  
  25.   
  26. }  

 

 


Tags: quot gt style lt savedInstanceState onCreate

文章來源:


ads
ads

相關文章
ads

相關文章

ad