单位转换、获取屏幕尺寸及在onCreate()方法中获取控件的宽度和高度
单位转换、获取屏幕尺寸及在onCreate()方法中获取控件的宽度和高度
1.dp转换为px
private int dp2px(int value,Context context) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,context.getResources().getDisplayMetrics() );
}
2.px转换为dp
public int px2dp(float pxValue) {
final float scale = this.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
3.sp转换为px
public int sp2px(context context, float spVal) {
return (int)TypedValue.applyDimension(TypedValue.COMPILE_UNIT_SP, spVal, context.getResources().getDisplayMetrics());
}
4.px转换为sp
public float px2sp(Context context, float pxVal) {
return (pxVal/context.getResources().getDisplayMetrics().scaledDensity);
}
5.获取屏幕宽度
public int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels();
}
6.获取屏幕高度
public int getScreenHeight(Context context)
return context.getResources().getDisplayMetrics().heightPixels();
}
7.在activity的onCreate()方法中获取控件的宽度和高度
view.post(new Runnable() {
@Override
public void run() {
int width = view.getWidth();
int height = view.getHeight();
}
});