java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料

保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。

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:

1
2
3
4
5
6
<MyView  
     android:&hellip;  
     &hellip;
     my:myviewtextsize=&rdquo;@dimen/textsize_24&Prime;  
     &hellip;  
/>

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

In MyView.java,

1
2
3
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:

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

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

因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。

后续会有更多的精彩的内容分享给大家。