Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

android - How to set text size using dimension from xml at runtime programmatically?

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).

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add dimension in dimens.xml:

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

Set the size in code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...