沉浸式状态栏的实现和版本兼容

来源:互联网 发布:xampp ubuntu安装 编辑:程序博客网 时间:2024/05/16 10:56

之前在项目中没有用到过沉浸式状态栏,也没有过分深究,在近期的项目中要实现沉浸式状态栏的效果,因此下了一番功夫好好好的深究了下。沉浸式状态栏是Android在5.0中进入,他是给状态栏着色的,看起来更加美观。在Android5.0中有特定的API供我们使用,但是在5.0之前是没有的,并且在Android6.0中沉浸式状态栏的使用方法和5.0还不一样,因此需要做到版本兼容,针对于不同的Android进行适配。下面是activity的基类,只要继承这个activity就可以实现沉浸式状态栏的效果,代码里面的注释很详细,相信大家都可以看懂。

1、基类BaseActivity的xml文件布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@color/guide_blue_shape"    android:clipToPadding="true"    android:fitsSystemWindows="true"></LinearLayout>

注意:一定要加上android:clipToPadding="true"      android:fitsSystemWindows="true"

2、基类BaseActivity的代码实现和版本兼容

public class BaseActivity extends AppCompatActivity {    public TextView view;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        initWindow();        setContentView(R.layout.activity_base);        //保证子类的activity能够正常的添加子布局,没有这个会导致子类无法添加布局        ViewGroup mContentView = (ViewGroup) getWindow().findViewById(Window.ID_ANDROID_CONTENT);        View mChildView = mContentView.getChildAt(0);        if (mChildView != null) {            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.            mChildView.setFitsSystemWindows(true);        }    }
   /**     * android api不同版本的状态栏处理     */    private void initWindow() {        if (Build.VERSION.SDK_INT >= 21) {            Vision21API();        } else if (Build.VERSION.SDK_INT >= 19) {            Vision19API();        }    }
    private void Vision19API() {        Window window = getWindow();        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);        ViewGroup decorViewGroup = (ViewGroup) window.getDecorView();        View statusBarView = new View(window.getContext());        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, UiUtils.dp2px(20));        params.gravity = Gravity.TOP;        statusBarView.setLayoutParams(params);        statusBarView.setBackgroundColor(Color.parseColor("#20a0e9"));        decorViewGroup.addView(statusBarView);    }
 @TargetApi(Build.VERSION_CODES.LOLLIPOP)    private void Vision21API() {        Window window = getWindow();        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);        //设置状态栏颜色        window.setStatusBarColor(Color.parseColor("#20a0e9"));    }}
0 0