一、概述
在项目中,测试发现在一些华为手机的屏幕适配上出现了问题,主要是因为华为Mate等一些系列的手机有一个虚拟按键的设计.当这些虚拟按键由用户手势滑出,或默认显示的话,就会遮挡我们本身的应用布局.比如欢迎界面过后是四个Fragment,那么底部的四个tab就会被虚拟的导航栏遮住,非常难看.
二、布局由于虚拟按键导致导航栏顶上去的解决方法
在我们的项目中加载Fragment的MainActivity,以及其他一般的Activity继承的BaseActivity中的onCreate方法中添加如下代码:
if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) { AndroidWorkaround.assistActivity(findViewById(android.R.id.content)); }其中AndroidWorkaround使我们为了解决该问题而封装的类,也可以看作是一个特定的工具类:
import android.content.Context; import android.content.res.Resources; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import java.lang.reflect.Method; /** *@desc *@method *@auth wenke *@date 2017-06-27 21:23 */ public class AndroidWorkaround { private int usableHeightPrevious; private ViewGroup.LayoutParams frameLayoutParams; public static void assistActivity(View content) { new AndroidWorkaround(content); } View mChildOfContent; private AndroidWorkaround(View content) { mChildOfContent = content; mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { possiblyResizeChildOfContent(); } }); frameLayoutParams = mChildOfContent.getLayoutParams(); } private void possiblyResizeChildOfContent() { int usableHeightNow = computeUsableHeight(); if (usableHeightNow != usableHeightPrevious) { frameLayoutParams.height = usableHeightNow; mChildOfContent.requestLayout(); usableHeightPrevious = usableHeightNow; } } private int computeUsableHeight() { Rect r = new Rect(); mChildOfContent.getWindowVisibleDisplayFrame(r); return (r.bottom); } public static boolean checkDeviceHasNavigationBar(Context context) { boolean hasNavigationBar = false; Resources rs = context.getResources(); int id = rs.getIdentifier("config_showNavigationBar", "bool", "android"); if (id > 0) { hasNavigationBar = rs.getBoolean(id); } try { Class systemPropertiesClass = Class.forName("android.os.SystemProperties"); Method m = systemPropertiesClass.getMethod("get", String.class); String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys"); if ("1".equals(navBarOverride)) { hasNavigationBar = false; } else if ("0".equals(navBarOverride)) { hasNavigationBar = true; } } catch (Exception e) { } return hasNavigationBar; } }