效果图如下,就是状态栏和actionbar保持一致的颜色,非常漂亮
在activity的onCreate 方法里调用该方法就好了。使用时,将R.color.blue换成自己喜欢的颜色
/** * 适配沉浸式状态栏,sdk 19 以上才有效 * <br>对全屏状态做了例外处理,全屏状态改变时需要调用此方法 */ @TargetApi(android.os.Build.VERSION_CODES.KITKAT) public static void immersive(ActionBarActivity activity) { if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) return; ColorDrawable bgColor = new ColorDrawable(activity.getResources().getColor(R.color.blue)); activity.getSupportActionBar().setBackgroundDrawable(bgColor); Window window = activity.getWindow(); int flags = window.getAttributes().flags; //非全屏 if ((flags | WindowManager.LayoutParams.FLAG_FULLSCREEN) != flags) { window.setFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); View contentView = window .findViewById(Window.ID_ANDROID_CONTENT); contentView.setBackground(bgColor); contentView.setPadding(0, getStatusbarHeight(activity), 0, 0); } else { //全屏 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); View contentView = window .findViewById(Window.ID_ANDROID_CONTENT); contentView.setBackground(bgColor); contentView.setPadding(0, 0, 0, 0); } } public static int getStatusbarHeight(Context context) { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object obj = c.newInstance(); Field field = c.getField("status_bar_height"); int x = Integer.parseInt(field.get(obj).toString()); int y = context.getResources().getDimensionPixelSize(x); return y; } catch (Exception e) { e.printStackTrace(); return (int) (context.getResources().getDisplayMetrics().density * 20 + 0.5); } }
时间: 2024-10-28 20:41:53