Android内容被底部虚拟导航栏遮挡解决

BaseActivity中设置

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //底部虚拟导航栏适配
    if (StatusBarUtil.hasNavigationBarShow(this)) {
        getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, StatusBarUtil.getNavigationBarHeight(this));
    }
}

StatusBarUtil工具类

public static boolean hasNavigationBarShow(Activity activity) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return false;
    }
    WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics();
    //获取整个屏幕的高度
    display.getRealMetrics(outMetrics);
    int heightPixels = outMetrics.heightPixels;
    int widthPixels = outMetrics.widthPixels;
    //获取内容展示部分的高度
    outMetrics = new DisplayMetrics();
    display.getMetrics(outMetrics);
    int heightPixelsContent = outMetrics.heightPixels;
    int widthPixelsContent = outMetrics.widthPixels;
    int h = heightPixels - heightPixelsContent;
    int w = widthPixels - widthPixelsContent;
    return w > 0 || h > 0;  //竖屏和横屏两种情况
}

/**
 * 获取导航栏高度
 *
 * @param context
 * @return
 */
public static int getNavigationBarHeight(Context context) {
    return getSystemComponentDimen(context, "navigation_bar_height");
}

public static int getSystemComponentDimen(Context context, String dimenName) {
    // 反射手机运行的类:android.R.dimen.status_bar_height.
    int statusHeight = -1;
    try {
        Class<?> clazz = Class.forName("com.android.internal.R$dimen");
        Object object = clazz.newInstance();
        String heightStr = clazz.getField(dimenName).get(object).toString();
        int height = Integer.parseInt(heightStr);
        //dp->px
        statusHeight = context.getResources().getDimensionPixelSize(height);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return statusHeight;
}
上一篇 Android使用Facebook的开放图谱发布图文分享
下一篇 Android在全屏下ScrollView包裹EditText软键盘弹出后,ScrollView无法滚动
目录
文章列表
1 Android NDK基础21:C++_继承_多态
Android NDK基础21:C++_继承_多态
2
Python列表
Python列表
3
高等数学基础:偏导数与方向导数
高等数学基础:偏导数与方向导数
4
Vue Cli 生成的项目性能优化总结
Vue Cli 生成的项目性能优化总结
5
常用开发工具整理
常用开发工具整理
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。