效果图:
一. 关于去标题栏
(1)继承Activity时,只需要在setContentView写入下面这行代码
requestWindowFeature(Window.FEATURE_NO_TITLE);
(2)继承AppCompatActivity时,(1)那样设置无效,需要在清单文件(AndroidManifest.xml)中更换主题
Theme.AppCompat.Light.NoActionBar、Theme.AppCompat.NoActionBar或Theme.AppCompat.DayNight.NoActionBar中的一个,即可隐藏标题栏。
设置成Theme.AppCompat.NoActionBar后,布局变成黑色背景,其他两种为白色背景。
下面两行代码的作用:
// getSupportActionBar().hide(); //隐藏标题栏,标题栏的位置依旧存在 // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //去状态栏
二. 设置沉浸式状态栏
(2)添加以下方法
private void initWindows() { Window window = getWindow(); int color = getResources().getColor(R.color.colorPrimary); //设置状态栏的颜色 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //设置状态栏颜色 window.setStatusBarColor(color); //设置导航栏颜色 window.setNavigationBarColor(color); ViewGroup contentView = ((ViewGroup) findViewById(android.R.id.content)); View childAt = contentView.getChildAt(0); if (childAt != null) { childAt.setFitsSystemWindows(true); } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //透明状态栏 window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏 window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //设置contentview为fitsSystemWindows ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content); View childAt = contentView.getChildAt(0); if (childAt != null) { childAt.setFitsSystemWindows(true); } //给statusbar着色 View view = new View(this); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(this))); view.setBackgroundColor(color); contentView.addView(view); } }
/** * 获取状态栏高度 * * @param context context * @return 状态栏高度 */ private static int getStatusBarHeight(Context context) { // 获得状态栏高度 int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); return context.getResources().getDimensionPixelSize(resourceId); }至此。