将TextView设置根据dimens.xml中值设置字体大小
2016-02-16 15:32
483 查看
注意:
TextView的setTextSize(float size))默认单位是sp,特别注意这个地方很容易犯错。
// dimens.xml中的定义<dimen name="my_text_size">22sp</dimen>
// 给一个id为name的TextView设置字体大小
以下提供两种方法:
方法1:
方法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); } }
相关文章推荐
- NameNode 和 Secondary NameNode 的区别和作用
- Java正则表达式详解
- 关于this
- Qt应用程序打包
- java常用算法之最长回文子串(Longest Palindromic Substring)
- 使用Badboy自动录制脚本
- if语句 return;结尾
- Fake API工具:interfake快速入门
- SQL语句中—删除数据
- C# ref和out 关键字
- 有关**迭代学习**控制的一些基本概念
- Wamp常见问题记录
- A way to CQRS and DDD
- hdu 1712 裸分组背包
- 3295: [Cqoi2011]动态逆序对 树状数组套主席树
- 深入理解abstract class和interface
- Android textview文字对齐换行问题
- js-读取系统时间
- Socket编程大总结
- iOS 【错误:'Changing the delegate of a tab bar managed by a tab bar controller is not allowed.'】