Android-沉浸式狀態列的實現

marcushbs發表於2020-10-13

1、取得狀態列的高度值

/**
     * 獲取狀態列的高度
     * @return
     */
    protected int getStatusBarHeight(){

        try {
            //通過反射獲取到類
            Class<?> aClass = Class.forName("com.android.internal.R$dimen");
            //建立物件
            Object o = aClass.newInstance();
            //拿取屬性
            Field status_bar_height = aClass.getField("status_bar_height");
            //獲取值
            Object o1 = status_bar_height.get(o);
            int height = Integer.parseInt(o1.toString());
            //
            return getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0 ;
    }

 

2、設定沉浸式狀態列(狀態列設定透明後,將頂層佈局高度動態增加狀態列的高度)

 /**
     * 系統版本4.4或以上才可以設定沉浸式狀態列
     *
     * 設定沉浸式狀態列
     */
    private void setStatus(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //設定狀態列透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //設定導航欄透明(如需要設定導航欄)
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            bar_layout = (ViewGroup) findViewById(R.id.bar_layout);
            final int statusBarHeight = getStatusBarHeight();
            bar_layout.post(new Runnable() {
                @Override
                public void run() {
                    int height = bar_layout.getHeight();
                    ViewGroup.LayoutParams layoutParams = bar_layout.getLayoutParams();

                    layoutParams.height = statusBarHeight + height ;
                    bar_layout.setLayoutParams(layoutParams);
                }
            });
        }
    }

 

相關文章