Android记录 透明状态栏+固化的沉浸模式的简单实现

代码中实现透明状态栏的方法:

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding _binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        translationStatusBar();
        _binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(_binding.getRoot());
    }
    // 透明状态栏
    private void translationStatusBar() {
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            // 此时使用 View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 时界面会和导航栏重叠
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        getSupportActionBar().hide();
    }
}

代码中简单实现固化的沉浸模式的方法:

public class MainActivity2 extends AppCompatActivity {
    private ActivityMainBinding _binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullscreenAndNoNavigation();
        _binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(_binding.getRoot());
    }
    // 沉浸模式
    private void setFullscreenAndNoNavigation() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
    }
    // 沉浸模式、保持
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //判断4.4以上版本
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            //获得DecorView
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE //来帮助你的app来维持一个稳定的布局
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION //确保appUI的主要部分不会因为被系统导航栏覆盖而结束
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN //确保appUI的主要部分不会因为被系统状态栏覆盖而结束
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //隐藏导航栏
                            | View.SYSTEM_UI_FLAG_FULLSCREEN //表示全屏,会将状态栏隐藏,只会隐藏状态栏
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

            // SYSTEM_UI_FLAG_IMMERSIVE 非粘性的沉浸式
            // SYSTEM_UI_FLAG_IMMERSIVE_STICKY 粘性的沉浸式
        }
    }
}

  

posted @ 2023-01-18 01:55  swalka`x  阅读(41)  评论(0编辑  收藏  举报