为.xml或编程方式设置文字大小 [英] Set text size in .xml or programmatically

查看:92
本文介绍了为.xml或编程方式设置文字大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dimens.xml变量

I have variable at dimens.xml

<resources>
    <dimen name="btn_text_size">12sp</dimen>    
</resources>

我可以在布局文件中使用它:

And i can use it in layout file:

 <TextView
           android:textSize="@dimen/btn_text_size"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/dialog_tags_complete"
/>

或编程

tagButton.setTextSize(c.getResources().getDimension(R.dimen.tag_text_size));

但是,这2种方法得出不同的结果。我知道, getDimension 基于与资源相关​​的电流DisplayMetrics。

But this 2 methods give different results. I know that getDimension are based on the current DisplayMetrics associated with the resources.

不过,我应该怎么做,使这2个方法看起来是一样的?

But what should i do to make this 2 ways looks the same?

推荐答案

setTextSize(浮点)预计缩放像素值。因此, setTextSize(12)会给你想要的结果。然而, getDimension() getDimensionPixelSize()返回像素大小的单位,所以你需要使用单位的-typed变种 setTextSize()如下:

setTextSize( float ) expects a scaled pixel value. So, setTextSize( 12 ) would give you the desired result. However, getDimension() and getDimensionPixelSize() return the size in units of pixels, so you need to use the unit-typed variant of setTextSize() as follows:

setTextSize( TypedValue.COMPLEX_UNIT_PX, getDimensionPixelSize( R.dimen.tag_text_size ) );

这篇关于为.xml或编程方式设置文字大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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