在我們編寫(xiě)自定義控件的時(shí)候常常會(huì)需要進(jìn)行單位轉(zhuǎn)換原探,這個(gè)時(shí)候莉兰,這個(gè)再熟悉不過(guò)的工具類(lèi)—— DisplayUtil 就會(huì)出現(xiàn)在我們的自定義控件中刊懈。
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DotViewLayout);
// 默認(rèn) indicator 間距 10dp
mIndicatorSpace = typedArray.getInt(R.styleable.DotViewLayout_indicator_space,
DisplayUtil.dip2px(context, 10));
DisplayUtil 源碼
public class DisplayUtil {
public static int px2dip(Context context, float px) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}
public static int dip2px(Context context, float dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
但是内狸,有時(shí)候又懶得 copy 這個(gè)工具類(lèi)灿里。后來(lái)發(fā)現(xiàn),Android Framework 是提供了相應(yīng)的工具類(lèi)供我們使用的俯逾。
TypedValue
中的 applyDimension()
方法:
/**
*
* @param unit The unit to convert from.
* @param value The value to apply the unit to.
* @param metrics Current display metrics to use in the conversion --
* supplies display density and scaling information.
*/
public static float applyDimension(int unit, float value,
DisplayMetrics metrics)
{
switch (unit) {
case COMPLEX_UNIT_PX:
return value;
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}
該方法將傳入的 value
值轉(zhuǎn)變?yōu)?strong>標(biāo)準(zhǔn)尺寸贸桶,那么我們的自定義控件就可以不用依賴(lài) DisplayUtil
。
之前的栗子就可以這么寫(xiě):
mIndicatorSpace = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,getResources().getDisplayMetrics());
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DotViewLayout);
// 默認(rèn) indicator 間距 10dp
mIndicatorSpace = typedArray.getInt(R.styleable.DotViewLayout_indicator_space,mIndicatorSpace);
筆者認(rèn)為:雖然自定義控件了多了好多代碼桌肴,但是皇筛,減少了對(duì) DisplayUtil
的依賴(lài)(哈哈,不用粘貼 DisplayUtil
了)坠七,我們的自定義控件發(fā)布時(shí)也變得 clean 多了水醋!