最近翻看了几篇博客,看看大神们对处理状态栏背景色的处理方式,大部分都是用到了第三方的一些jar,讲的很细,很是佩服,不过我比较懒,发现一种偷懒的方式解决状态栏背景色修改问题。
下面给出我的布局代码
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:id="@+id/status_bar_view" android:layout_width="match_parent" android:layout_height="25dp" android:layout_alignParentTop="true" android:background="@color/colorAccent" > </RelativeLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/status_bar_view" android:background="@color/colorAccent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:padding="10dp" android:text="Back" android:textColor="@color/white" android:textSize="18sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="10dp" android:text="Title" android:textColor="@color/white" android:textSize="18sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:padding="10dp" android:text="Sure" android:textColor="@color/white" android:textSize="18sp"/> </RelativeLayout> </RelativeLayout>
常规布局 肯定是你熟悉并且常用的布局
我们来看下效果
当然光靠这布局,是看不出来这种效果的,还需要对代码配合
下面给出我的代码
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) { //透明状态栏 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); RelativeLayout statusBars = (RelativeLayout) findViewById(R.id.status_bar_view); //如果是API19及以上的版本 这样处理 否则就要隐藏了 if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT) { statusBars.setBackgroundResource(R.color.blue); }else{ statusBars.setVisibility(View.GONE); } }代码很简单就这么多,效果如下
至此完了,就这么多代码,没有依赖任何第三方的东西。
值得一提的是,一般都是基于API19以上的版本来操作的,我这种做法也不例外。我就是偷了个懒。对状态栏设置透明后会引起高度丢失的问题,试过其他博客中提到的在根布局或者最靠近根布局的那个控件中设置如下属性
android:clipToPadding="true" android:fitsSystemWindows="true"
但是效果不理想,于是就想到了这个方法。
条条大道去罗马,能实现你想要的效果这才是最终目的。