将TextView设置根据dimens.xml中值设置字体大小
发布时间:2020-12-16 05:56:30 所属栏目:百科 来源:网络整理
导读:注意: 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为na
注意:
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> 以下提供两种方法: 方法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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |