如何在程序运行时使用xml中的标注来设置文本大小? [英] How to set text size using dimension from xml at runtime programmatically?

查看:66
本文介绍了如何在程序运行时使用xml中的标注来设置文本大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在dimens.xml中,我有:

In dimens.xml, I have:

<dimen name="text_medium">18sp</dimen>

在运行时,我得到此值并设置文本视图的文本大小:

In runtime, I get this value and set the text size of a text view:

int size = context.getResources().getDimensionPixelSize(R.dimen.text_medium);
textView.setTextSize(size).

在10英寸平板电脑(1280 x 800)上,一切正常.但是在电话(800 x 480)上,文本视图的字体很大.在平板电脑上,大小等于18;在平板电脑上,在电话上是27.

On a 10″ tablet (1280 x 800), everything is ok; but on a phone (800 x 480), the text view has a very large font. On the tablet, the size equals 18; on the phone, it's 27.

如果我通过以下方式手动设置尺寸:

If I set the size manually by:

textView.setTextSize(size)

两个设备上的大小均正常.

the size is normal on both devices.

推荐答案

dimens.xml 中添加维度:

   <dimen name="text_medium">18sp</dimen>

在代码中设置大小:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));

这篇关于如何在程序运行时使用xml中的标注来设置文本大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆