最近项目里面要用到沉浸式开发,在网上查了好多资料,发现并不适合我们的项目,一般的做法是把布局设成全屏模式,利用 ChildView 的 fitsSystemWindows 属性来控制位置,但当我这样做了以后发现我们的layout是以整个屏幕的左上角为基准,也就是整个layout向上移动了一个状态栏的高度,所以我自己改善了一下,用了另外一种方式,先移除这个DecorView中的布局,然后手动设置我们layout的padingTop值
代码如下
public class SetContentViewUtils { public static void setView(Activity activity,int id){ LayoutInflater layoutInflater = LayoutInflater.from(activity); setTranslucentStatus(activity); ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content); int height = getStatusBarHeight(activity); ViewGroup linearLayout = (ViewGroup) layoutInflater.from(activity).inflate(id,null); linearLayout.setPadding(0,height,0,0); decorView.removeAllViews(); decorView.addView(linearLayout); } private static int getStatusBarHeight(Activity activity) { Class<?> c = null; Object obj = null; Field field = null; int x = 0, sbar = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); sbar = activity.getResources().getDimensionPixelSize(x); return sbar; } catch (Exception e1) { // loge("get status bar height fail"); e1.printStackTrace(); return 0; } } /** * 设置状态栏背景状态 */ private static void setTranslucentStatus(Activity context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window win = context.getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; winParams.flags |= bits; win.setAttributes(winParams); } } }直接在代码中这样使用就行了
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SetContentViewUtils.setView(this,R.layout.activity_main2); }状态栏的值就是layout根布局的颜色的值
github地址:https://github.com/zhouwei5200/Immersive