开发者

how do I automatically adjust textSize in android?

开发者 https://www.devze.com 2023-02-22 21:19 出处:网络
I am writing an app, in which part of it displays a line of text. there are certain scenarios where that line of te开发者_开发知识库xt will take up more than one line. the problem is that I only want

I am writing an app, in which part of it displays a line of text. there are certain scenarios where that line of te开发者_开发知识库xt will take up more than one line. the problem is that I only want it to take up one line, and when I set it up either in java or in xml to only take up one line, the text is cut off. how would I make it so that it automatically adjusts the font size of the text so that it will only take up one line without being cut off?


Use proportions along with Paint.measureText():

(text size / measureText width) = (perfectSize / screenWidth)

Solving for the perfect text size:

perfectSize = (text size / measureText width) * screenWidth;

You can find the screen width with getWindowManager().getDefaultDisplay().getWidth() from the Display class.

Turned it into a math problem!


This isn't too hard to do if you use Paint#measureText.

Basically you would start with a font height smaller than the height of your TextView and then iterate (or do a binary search) through fonts of varying sizes until you find one that measures to smaller than the width of your TextView.

It requires some implementation, as there is no "automatic" way provided by the framework.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号