Android隐藏头部状态栏

前言

在研究APP写了很多demo的时候我发现顶部有一个状态栏(ActionBar)在用不到它的时候就会显得很丑而且还占地方,所以得想个办法把它隐藏起来。

首先贴上官网介绍的方法

隐藏状态栏  |  Android 开发者  |  Android Developers

在Android4.1之后,如果Activity继承的是Application,则用官方介绍的办法来隐藏状态栏

    View decorView = getWindow().getDecorView();
    // Hide the status bar.
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
    decorView.setSystemUiVisibility(uiOptions);
    // Remember that you should never show the action bar if the
    // status bar is hidden, so hide that too if necessary.
    ActionBar actionBar = getActionBar();
    actionBar.hide();
    

但是!

我发现官网介绍的办法运行了报错,我用debug看了下发现我用getActionBar()方法获取为null,在我查了很多资料后发现——如果Activity继承了Appcompat,则必须使用getSupportActionBar()来获取ActionBar

            View decorView = getWindow().getDecorView();
            // Hide the status bar.
            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
            // Remember that you should never show the action bar if the
            // status bar is hidden, so hide that too if necessary.
            //ActionBar actionBar = getActionBar();
            ActionBar actionBar = getSupportActionBar();
            if(actionBar != null){
                actionBar.hide();
            }

猜你喜欢

转载自blog.csdn.net/TDSSS/article/details/126352205
今日推荐