Android获取状态栏高度

    xiaoxiao2021-04-01  38

    获取状态栏高度有两种方法: 1.如果是在Activity中: Rect localRect = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); statusHeight = localRect.top; 限制:由于getWindow()方法在Activity中,所以只能在Activity中使用 ,当然了,如果你传递的context对象可以被强转成Activity,那也可以,如下: ((Activity)mContext).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect); 如果不能强转,而又不在activity中,还可以利用反射机制获取,这种方法只要有context对象就可以使用: private 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; }
    转载请注明原文地址: https://ju.6miu.com/read-665524.html

    最新回复(0)