乐趣区

Android状态栏与页面顶部内容重合解决方案

在项目的开发过程中 , 发现创建 activity 界面后 , 界面顶部的返回按钮被状态栏遮挡住一部分 , 在点击返回的时候, 很难触发点击事件, 页面也不太美观, 话不多说, 直接上代码.

计算状态栏高度的工具类:

public class StatusBarUtil {

    // 获取状态栏高度
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {e1.printStackTrace();
        }
        return statusBarHeight;
    }

}

在 activity 中重写 onWindowFocusChanged() 方法:

@Override
    public void onWindowFocusChanged(boolean hasFocus) {super.onWindowFocusChanged(hasFocus);
        // 设置第一个 view 距离状态栏的高度;LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rlLinearLayout.getLayoutParams();//rlLinearLayout 为遮挡住的页面布局 LinearLayout
        int top = StatusBarUtil.getStatusBarHeight(this);// 获取状态栏高度
        lp.topMargin = top;
         rlLinearLayout.setLayoutParams(lp);
 }

 总结:解决该问题的方案主要是: 计算出状态栏的高度 , 然后用代码的形式将页面顶部布局向下移状态栏的高度 , 解决方案还是比较简单的.

以下是个人公众号,之后发布的文章会同步到该公众号,方便交流学习 Android 知识及分享个人爱好文章:

退出移动版