Android 如何为 TextView 设置最小宽度(以字符为单位)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3188719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set a minimum width (in characters) for a TextView?
提问by If This Is Art
I've had a good search for this on here and can't find a solution.
我已经很好地搜索了here,但找不到解决方案。
I have a TextView in a RelativeLayout which contains an integer number. The number will range between 1 and 99 - can anyone tell me how to size the TextView so that its width is always the width of the string "99" even if it only contains "1"?
我在一个包含整数的 RelativeLayout 中有一个 TextView。该数字的范围在 1 到 99 之间 - 谁能告诉我如何调整 TextView 的大小,使其宽度始终是字符串“99”的宽度,即使它只包含“1”?
I need this because the positions of the components to the right of this TextView depend on its width, so all are position depending on how many digits the TextView contains.
我需要这个,因为这个 TextView 右侧的组件的位置取决于它的宽度,所以所有的位置都取决于 TextView 包含的数字数量。
I don't mind if this is done in XML or code - I just want to avoid having to set the width of a TextView in pixels!
我不介意这是用 XML 还是代码完成的 - 我只是想避免必须以像素为单位设置 TextView 的宽度!
Thanks for any possible solutions; Please ask if I've missed out any important info!
感谢您提供任何可能的解决方案;请问我是否遗漏了任何重要信息!
回答by Adrian
try this:
尝试这个:
android:layout_width="wrap_content"
android:minEms="2"
回答by pforhan
Ems works if your font is monospace. For proportional fonts, you want it the width of two '0's, not two 'm's. You can fall back to TextPaint.measureText like so:
如果您的字体是等宽字体,则 Ems 有效。对于比例字体,您希望它的宽度为两个“0”,而不是两个“m”。你可以像这样回到 TextPaint.measureText :
float measureText = zip.getPaint().measureText("00000");
zip.setWidth(zip.getPaddingLeft() + zip.getPaddingRight() + (int) measureText);
回答by Andriy Shpek
Best way is to use TextPaint
. Here is a simple example:
最好的方法是使用TextPaint
. 这是一个简单的例子:
TextPaint textPaint = new TextPaint();
textPaint.setTextSize(yourTextView.getTextSize());
yourTextView.setMinWidth((int) textPaint.measureText("-88.88"));
Do not forget to specify text size in your TextPaint object
In measureText
enter longest possible string you're expecting to see (I've written "-88.88" assuming my text can handle positive or negative numbers below 100 with 2 digits after comma)
不要忘记在 TextPaint 对象中指定文本大小
在measureText
输入您希望看到的最长字符串中(我写了“-88.88”,假设我的文本可以处理 100 以下的正数或负数,逗号后有 2 位数字)
回答by Zsombor Erd?dy-Nagy
I think you're looking for the getTextBounds() method in the Paint class. Didn't try it myself tho.
我认为您正在寻找 Paint 类中的 getTextBounds() 方法。自己没试过。