【第22期】观点:IT 行业加班,到底有没有价值?

Units Problem: How to read text size as custom attr from xml and set it to TextView in java code

原创 2013年12月05日 11:08:43

Here is this topic’s background:

I defined a custom View which extends FrameLayout and contains a TextView, calledMyView here. And I defined custom attribute “myviewtextsize” in attrs.xml for MyView so that clients can set different text size in layout xml for the TextView of MyView.

So far, clients code can set text size like this:

<MyView
     android:…
     ….
     my:myviewtextsize=”@dimen/textsize_24″
     ….
/>

The problem is: how to read the client’s text size number and set it to the TextVew of MyView?

In MyView.java,

float textSize = typedArray.getDimension(R.MyView_myviewtextsize, -1);

this.textView.setTextSize(textSize).


Above code goes wrong. The text size is bigger than it’s supposed to.

Why? It is mixed units problem.

The default method setTextSize(float) assumes you’re inputting sp units (scaled pixels), while the typedArray.getDimension() method returns an exact pixel size.

It can be fixed this by using the alternate setTextSize(TypedValue, float), like below:

this.textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

This will make sure you’re working with the same units.

版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

How to generate UML Diagrams from Java code in Eclipse

How to generate UML Diagrams from Java code in Eclipse UML diagrams compliment inline docum...

How to read xml use JDOM in java application

刚才写了一篇create xml文件用JDOM来生成,那么下面我来说说如何取出里面的内容 我只是做个事例,其他的都差不多!! 代码如下 import java.io.FileInputStream; import java.io.FileNotFoundException; import java....

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

Android: How to download the latest zip Android Source Code easily and using it in Intellij

http://geekycoder.wordpress.com/2009/07/03/how-to-download-latest-zip-android-source-code-and-using-...

How to print stack trace in your java code?

When debugging java code, sometimes it's important to know where you come from. So you can print current stack trace to help you.   1. new ...

Units Problem: How to read text size as custom attr from xml and set it to TextView in java code

Here is this topic’s background:I defined a custom View which extends FrameLayout and contains a Tex...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)