android沉浸式开发

最近项目里面要用到沉浸式开发,在网上查了好多资料,发现并不适合我们的项目,一般的做法是把布局设成全屏模式,利用 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值