Android-沉浸式狀態欄的實現

一、取得狀態欄的高度值android

/**
     * 獲取狀態欄的高度
     * @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 ;
    }

 

二、設置沉浸式狀態欄(狀態欄設置透明後,將頂層佈局高度動態增長狀態欄的高度)ide

 /**
     * 系統版本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);
                }
            });
        }
    }
相關文章
相關標籤/搜索