美文网首页Android安卓Android
android 中 获取各种高度,控件,状态栏,底部导航栏

android 中 获取各种高度,控件,状态栏,底部导航栏

作者: 追梦小乐 | 来源:发表于2018-08-24 23:46 被阅读168次

    转载简书博主:差得很远呢 的文章
    https://www.jianshu.com/p/c1f2a3849d6e

    状态栏即statusBar,导航栏即某些手机底部有返回键的虚拟键那一栏,叫navigationBar。

    1. 获取顶部statusBar高度
    private int getStatusBarHeight() {
        Resources resources = mActivity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Status height:" + height);
        return height;
    }
    
    2. 获取底部navigationBar高度
    private int getNavigationBarHeight() {
        Resources resources = mActivity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Navi height:" + height);
        return height;
    }
    
    3. 获取设备是否存在NavigationBar
    //获取是否存在NavigationBar
        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;
    
        }
    
    4. 在页面未加载出来前,获取控件的宽高
        view.post(new Runnable() {
           @Override
            public void run() {
               int viewWidth = view.getWidth();//view宽度
                    int viewHeight = view.getHeight();//view高度
                }
        });
    
    5. 获取屏幕宽度

    在页面未加载出来前,直接通过getWidth()获取的宽度为0,即使你在onResume()方法中执行这个方法也是一样。

        public static int getScreenWidth(Context context) {
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            return dm.widthPixels;
        }
    
    6. 获取屏幕高度
        public static int getScreenHeight(Context context) {
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            return dm.heightPixels;
        }
    

    相关文章

      网友评论

      • shunxir:第四条有误,运行run方法时已经至少加载一帧了

      本文标题:android 中 获取各种高度,控件,状态栏,底部导航栏

      本文链接:https://www.haomeiwen.com/subject/tnhwiftx.html