说起沉浸式状态栏,大家都不陌生,而且大家都能实现,不管是自己做的还是用第三方的库,都能很完美的实现,不过呢,今天想跟大家分享的是这样的一个需求:视频类APP,竖屏的时候显示我们自定义的沉浸式状态栏,横屏隐藏掉沉浸式状态栏。就这么简单的一个需求,我搞了一天,问了很多大神,比如代码家,陈宇明等
收到的回复都是不好做,我当时就崩溃了,大神都不会,菜鸟的我该如何是好?当时就下定决心,一定要做出来!于是,我看了开源库systembartint的源代码,发现也没有相关的方法去实现,(首先要说的是,竖屏的沉浸式是很容易实现,但是横屏隐藏沉浸式就有点难了),我们来看看竖屏状态下的沉浸式是怎么实现的:
public static void setdrawableActivity(Activity activity, int drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); View statusView = createStatusBarViewdrawable(activity, drawable); ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); decorView.addView(statusView); setRootViewdrawable(activity); } }
这段代码最关键的是在
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); decorView.addView(statusView);
在屏幕的上方添加一个状态栏,而这个状态栏就是我们自定义的(用颜色,也可以用图片)
看到这里我就有点窃喜了,因为有添加就有移除,大家是不是想到了,对,就是
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();decorView.removeView(statusBarView);
这个方法就是解决我们遇到的问题的关键之处。好啦,不卖关子了,上代码:
public static void setdrawableActivity(Activity activity, int drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
View statusView = createStatusBarViewdrawable(activity, drawable);
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(statusView);
setRootViewdrawable(activity);
}
}
public static void remove(Activity activity) {
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.removeView(statusBarView);
setRootViewdrawable(activity); }
private static View createStatusBarViewdrawable(Activity activity, int drawable) {
statusBarView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight(activity));
statusBarView.setLayoutParams(params);
statusBarView.setBackgroundDrawable(activity.getResources().getDrawable(drawable));
return statusBarView;
}
private static void setRootViewdrawable(Activity activity) {
ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
rootView.setFitsSystemWindows(true);
rootView.setClipToPadding(true);
}
最后呈现的界面就是这样子,有点丑,大神勿喷!
QQ截图20160527110134.png
QQ截图20160527110213.png
网友评论