這是很不錯的方式昆烁,我不懂為什么用的人那么少吊骤,今天就來用一下吧。
public static float dp2px(int values){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,values,
Resources.getSystem().getDisplayMetrics());
}
其中 TypedValue 是 Android 一個工具類静尼,
/*
unit 表示單位白粉,
COMPLEX_UNIT_PX
COMPLEX_UNIT_DIP
COMPLEX_UNIT_SP
COMPLEX_UNIT_PT
COMPLEX_UNIT_IN
COMPLEX_UNIT_MM
values: 表示要轉(zhuǎn)化的值
DisplayMetrics:屏幕參數(shù)
*/
TypeValues.applyDimension(int unit,int values, DisplayMetrics dm)
為什么可以不用上下文環(huán)境呢?
Resources.getSystem() 這個類在 Android 源碼中的解釋:
/*
Return a global shared Resources object that provides access to only system
resources (no application resources), is not configured for the current screen
(can not use dimension units, does not change based on orientation, etc),
and is not affected by Runtime Resource Overlay.
*/
這個方法可以提供與運(yùn)行時無關(guān)的參數(shù)鼠渺,比如屏幕的參數(shù)