转载请标明原地址:http://blog.csdn.net/u012258494/article/details/71215530
参考了网上的很多方法,实现了状态栏透明,即状态栏和标题栏颜色一致。特此总结一下,以下方法适用于布局里没有EditText控件的情况下:
1、values/styles中定义app基本主题AppTheme,适配4.4以下非透明状态栏 <style name="AppTheme" parent="@style/BaseTheme"/> <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> 2、values-v19/styles定义4.4及以上版本theme,使能状态栏透明 <style name="AppTheme" parent="@style/BaseTheme"> <!--<item name="android:windowTranslucentNavigation">true</item>--> <item name="android:windowTranslucentStatus">true</item> </style> 3、(1)如果activity包含toolbar布局,想要实现状态栏透明,则须在toolbar中添加android:fitsSystemWindows=”true”,作用为在toolbar增加25dp的paddingTop,同时须设置android:minHeight,否则在5.0时状态栏高度会不正常。 <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:fitsSystemWindows="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay"> </android.support.v7.widget.Toolbar>然后在activity的onCreate方法中添加代码
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //5.0及以上版本时,需要手动设置状态栏颜色为透明才能真正透明;4.4时style设为透明状态就可真正透明 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } 3、(2)如果activity为全屏图片,想要实现状态栏透明,则activity布局为 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/splash_root" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg_welcome" android:fitsSystemWindows="true" tools:context=".activity.SplashActivity"> </RelativeLayout>然后在activity的onCreate方法中添加代码
//5.0及以上版本时,需要手动设置状态栏颜色为透明才能真正透明;4.4时style设为透明状态就可真正透明 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); }ps:如果布局有EditText,则软键盘弹出时会因fitsSystemWindows而与toolBar冲突,可以参考沉浸式状态栏实现及遇到的坑 和Android – 设置透明状态栏后弹出键盘的时候Toolbar被拉伸或者移出屏幕的问题解决 这两篇文章来进行修改。
OK!!!
