Android-沉浸式状态栏的实现
程序员文章站
2022-05-03 10:34:51
1、取得状态栏的高度值 2、设置沉浸式状态栏(状态栏设置透明后,将顶层布局高度动态增加状态栏的高度) ......
1、取得状态栏的高度值
/** * 获取状态栏的高度 * @return */ protected int getstatusbarheight(){ try { //通过反射获取到类 class<?> aclass = class.forname("com.android.internal.r$dimen"); //创建对象 object o = aclass.newinstance(); //拿取属性 field status_bar_height = aclass.getfield("status_bar_height"); //获取值 object o1 = status_bar_height.get(o); int height = integer.parseint(o1.tostring()); // return getresources().getdimensionpixelsize(height); } catch (exception e) { e.printstacktrace(); } return 0 ; }
2、设置沉浸式状态栏(状态栏设置透明后,将顶层布局高度动态增加状态栏的高度)
/** * 系统版本4.4或以上才可以设置沉浸式状态栏 * * 设置沉浸式状态栏 */ private void setstatus(){ if(build.version.sdk_int >= build.version_codes.kitkat) { //设置状态栏透明 getwindow().addflags(windowmanager.layoutparams.flag_translucent_status); //设置导航栏透明(如需要设置导航栏) getwindow().addflags(windowmanager.layoutparams.flag_translucent_navigation); bar_layout = (viewgroup) findviewbyid(r.id.bar_layout); final int statusbarheight = getstatusbarheight(); bar_layout.post(new runnable() { @override public void run() { int height = bar_layout.getheight(); viewgroup.layoutparams layoutparams = bar_layout.getlayoutparams(); layoutparams.height = statusbarheight + height ; bar_layout.setlayoutparams(layoutparams); } }); } }