Android解决虚拟按键栏遮挡问题
最近在公司的项目中 , 华为用户反馈出了一个问题 , 华为手机底部有虚拟按键栏把应用的底部内容遮挡住了 , 现在已经把这个问题解决了 , 记录一下,给各位遇到相同问题的童鞋做一下参考.
这里的解决方案还是相对比较简单的,首先判断用户的手机是否存在虚拟按键,若存在,那么就获取虚拟按键的高度,然后再用代码设置相同高度的TextView,这样手机的虚拟按键就不会将底部的内容遮挡住了。
处理虚拟按键栏工具类:
public class ScreenUtils {//获取虚拟按键的高度public static int getNavigationBarHeight(Context context) {int result = 0;if (hasNavBar(context)) {Resources res = context.getResources();int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");if (resourceId > 0) {result = res.getDimensionPixelSize(resourceId);}}return result;}/*** 检查是否存在虚拟按键栏** @param context* @return*/(Build.VERSION_CODES.ICE_CREAM_SANDWICH)public static boolean hasNavBar(Context context) {Resources res = context.getResources();//读取系统资源函数int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");//获取资源idif (resourceId != 0) {boolean hasNav = res.getBoolean(resourceId);// check override flagString sNavBarOverride = getNavBarOverride();if ("1".equals(sNavBarOverride)) {hasNav = false;} else if ("0".equals(sNavBarOverride)) {hasNav = true;}return hasNav;} else { // fallbackreturn !ViewConfiguration.get(context).hasPermanentMenuKey();}}/*** 判断虚拟按键栏是否重写* @return*/private static String getNavBarOverride() {String sNavBarOverride = null;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {try {Class c = Class.forName("android.os.SystemProperties");Method m = c.getDeclaredMethod("get", String.class);m.setAccessible(true);sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");} catch (Throwable e) {}}return sNavBarOverride;}}
调用工具类方法 , 获取虚拟按键高度:
//处理虚拟按键//判断用户手机机型是否有虚拟按键栏if(ScreenUtils.hasNavBar(getApplicationContext())){setNavigationBar();}//处理虚拟按键private void setNavigationBar() {int barHeight = ScreenUtils.getNavigationBarHeight(getApplicationContext());LinearLayout.LayoutParams barParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);TextView tv = new TextView(this);tv.setHeight(barHeight);tv.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);tv.setBackgroundColor(Color.BLACK);llNavigationBar.addView(tv,barParams);}
到这里就结束啦!
评论
