您的位置:首页 > 其它

将TextView设置根据dimens.xml中值设置字体大小

2016-02-16 15:32 483 查看
注意:
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: