获取控件宽高

转发https://blog.csdn.net/lilu_leo/article/details/22722629

1.获取屏幕宽高px

 WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();

2.获取imageView宽高,由于会获取两次,所以需要在里面取消监听

        final ImageView imageView= findViewById(R.id.login_member);
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                android.util.Log.d("1111","imageView width:"+imageView.getMeasuredWidth());
            }
        });

3.获取屏幕dpi

 DisplayMetrics dm = new DisplayMetrics();
        dm = this.getApplicationContext().getResources().getDisplayMetrics();
        android.util.Log.d("11111","dpi:"+dm.densityDpi);

4.获取安卓屏幕

    public static void getAndroiodScreenProperty(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度(像素)
        int height = dm.heightPixels;       // 屏幕高度(像素)
        float density = dm.density;         // 屏幕密度(0.75 / 1.0 / 1.5)
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi(120 / 160 / 240)
        // 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)


        Log.d("h_bl", "屏幕宽度(像素):" + width);
        Log.d("h_bl", "屏幕高度(像素):" + height);
        Log.d("h_bl", "屏幕密度(0.75 / 1.0 / 1.5):" + density);
        Log.d("h_bl", "屏幕密度dpi(120 / 160 / 240):" + densityDpi);
        Log.d("h_bl", "屏幕宽度(dp):" + screenWidth);
        Log.d("h_bl", "屏幕高度(dp):" + screenHeight);
    }

你可能感兴趣的:(Android)