Android 获取屏幕和控件大小

  • Post author:
  • Post category:其他




屏幕大小

在这里插入图片描述

通过传上下文获取

  int width = this.getResources().getDisplayMetrics().widthPixels;
        int height = this.getResources().getDisplayMetrics().heightPixels;

大部分不包含虚拟键大小,包含了通知栏大小。得到的单位是px。

px:即像素,1px代表屏幕上一个物理的像素点

dp:屏幕像素,与屏幕密度有关。



转换方法

class ScreenUtil {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}



控件大小

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        // width:2560  height:1654
        Log.i("layout", "width:" + layMian.getMeasuredWidth() + "height:" + layMian.getMeasuredHeight());
    }



设置控件大小

 //设置的是像素px
        test.setWidth(width / 2);
        test.setHeight(height / 2);

建议:

文字的尺寸一律用sp单位,非文字的尺寸一律使用dp单位。例如textSize=“16sp”、layout_width=“60dp”;

偶尔需要使用px单位,例如需要在屏幕上画一条细的分隔线时:



版权声明:本文为weixin_43950528原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。