android之获取屏幕宽度、控件宽度

来源:互联网 发布:表格删除重复数据 编辑:程序博客网 时间:2024/05/12 18:18

1、获取屏幕宽度

屏幕宽度可以直接在activity的onCreate中获取,但控件宽度却不能,获取单位为px像素

DisplayMetrics dm = getResources().getDisplayMetrics();
int screenwidth = dm.widthPixels;
int screenheight = dm.heightPixels;


2、获取控件宽高及位置

在activity的onWindowFocusChanged(boolean hasFocous)中获取

@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
int[] location = new int[2];           //location[0] 为x坐标 location[1]为y坐标
textView1.getLocationInWindow(location);     //该方法获取的坐标是相对父窗口的坐标
//textView1.getLocationOnScreen(location);   //该方法获取的是整个屏幕内绝对坐标,包括通知栏
int width = v1.getWidth();                 //获取控件的宽度  单位为px
super.onWindowFocusChanged(hasFocus);
}


3、px和dp  之间的转换

public class DensityUtil {


/**
* 根据手机的分辨率从 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);
}
}








0 0
原创粉丝点击