Android Activity旋转屏幕横屏实现全屏方法

activity在竖屏的时候,顶部会有状态栏,顶部会有ToolBar,现在需求是,旋转屏幕以后,横屏状态下 整个界面是以全屏状态显示,隐藏ToolBar,不显示屏幕最顶部的状态栏

首先,在AndroidManiFest里面设置Activity的属性:

           
    android:name=".MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:screenOrientation="sensor"
    />

然后,在Activity中重写onConfigurationChanged方法,代码如下:

private boolean portrait;

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    portrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
    tryFullScreen(!portrait);
}

private void tryFullScreen(boolean fullScreen) {
    if (activity instanceof AppCompatActivity) {
        ActionBar supportActionBar = ((AppCompatActivity) activity).getSupportActionBar();
        if (supportActionBar != null) {
            if (fullScreen) {
                supportActionBar.hide();
            } else {
                supportActionBar.show();
            }
        }
    }
    setFullScreen(fullScreen);
}


private void setFullScreen(boolean fullScreen) {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        if (fullScreen) {
            attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(attrs);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

}
这样就能实现自动旋转屏幕,并且全屏的需求了

你可能感兴趣的:(安卓开发)