Android - 通过字符串修复 TextView 宽度
我认为这个问题的答案可能很简单,但我很挣扎......
我有一个包含多列的 TableLayout。我希望最后一列具有固定宽度,但我想定义该宽度以便能够容纳程序中尽可能宽的字符串。即它总是足够宽以包含“THIS STRING”而不会换行或浪费任何空间。
我想这样做,因为我在 ListView 中有这些 TableLayout,所以当最后一列的宽度可变时,它看起来很差。
我尝试获取字符串宽度,甚至将其放入 TextView 中,在所有适当的 TextView 上调用 getTextSize() 然后 setWidth() 。我遇到的问题是 gettextSize() 返回像素,但 setWidth 使用 ScaledPixels。
我确信有一个非常简单的解决方案。有人可以帮忙吗?
I think the answer to this question is probably so simple, but I'm struggling....
I have a TableLayout with multiple columns. I want the last column to be of a fixed width, but I want to define that width to just be able to hold the widest possible string from my program. i.e. it is always wide enough to contain "THIS STRING" without wrapping, or wasting any space.
I would like to do this as I have these TableLayouts within a ListView, so it looks very poor when the last column is of variable widths.
I have tried obtaining the string width, even going so far as to put it into a TextView, call getTextSize() then setWidth() on all appropriate TextViews. The problem I hit there is that gettextSize() returns pixels, but setWidth uses ScaledPixels.
I'm sure there is a really simple solution. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在 XML 布局中使用 android:width="wrap_content" 来定义最后一列的宽度?
编辑:我想我刚刚明白,您有一个列表视图,其中包含一个表格,并且您希望列表视图的所有行对于表格的最后一行具有相同的长度。正确的?
我现在只能想到一种非常不优雅的解决方案,它涉及在构建列表视图之前检查所有字符串。
一般逻辑如下:
我假设您从数组中获取所有字符串,我们称之为数据。
建立一个全局浮点变量来表示最长的字符串,我们称之为 maxLength。
在布局中创建一个不可见的文本视图(让我们称之为不可见文本),您可以通过设置
然后来做到这一点:
在列表视图构造函数中:
表格列应使用 android:width="wrap_content"
我没有测试这段代码,但它应该可以工作,我以前做过类似的事情。
Are you using android:width="wrap_content" in your XML layout to define the width of that last column?
Edit: I think I just understood, you have a list view, that holds a table and you want all rows of the list view to have the same length for the last row of the table. Right?
I can only think of one, very unelegant solution right now and it involves going over all strings before building the list view.
The general logic would be as follows:
Im going to suppose you are getting al strings from an array, lets call it data.
Establish a global float variable to represent the longest string you have, lets call it maxLength.
Create a textview (lets call it invisibleText) in your layout that wont be visible, you can do this by setting
Then:
In you list view constructor:
The table columns should use android:width="wrap_content"
I didnt test this code, but it should work, i've done similar stuff before.