注意:
方法2:
TextView的setTextSize(float size))默认单位是sp,特别注意这个地方很容易犯错。
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
// dimens.xml中的定义<dimen name="my_text_size">22sp</dimen>
// 给一个id为name的TextView设置字体大小
以下提供两种方法:
方法1:
TextView mName = (TextView)findViewById(R.id.name);
mName.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.my_text_size));
方法2:
TextView mName = (TextView)findViewById(R.id.name);
mName.setTextSize(DensityUtil.px2sp(context, getResources().getDimensionPixelSize(R.dimen.my_text_size)));
public class DensityUtil {
/**
* dip 2 px
* @param context
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
return (int) (dipValue * context.getResources().getDisplayMetrics().density + 0.5f);
}
/**
* px 2 dip
* @param context
* @param pxValue
* @return
*/
public static int px2dip(Context context, float pxValue) {
return (int) (pxValue / context.getResources().getDisplayMetrics().density + 0.5f);
}
/**
* sp 2 px
* @param context
* @param spValue
* @return
*/
public static int sp2px(Context context, float spValue) {
return (int) (spValue * context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
}
/**
* px 2 sp
* @param context
* @param pxValue
* @return
*/
public static int px2sp(Context context, float pxValue) {
return (int) (pxValue / context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
}
}