我很难想出一个可行的布局。我有一个填满屏幕宽度的 View 。它包含三个 subview :
- 一些文字
- 正文后括号中的数字
- 一个按钮
按钮右对齐,文本项依次左对齐,如图:
| Some heading text (n) [button] |
问题在于控制文本太长时发生的情况。我想要这样,以便数字始终在正文右侧可见。如果需要,应截断主要文本,以便其他两个 View 保持可见。
| Some very very long headin... (n) [button] |
我得到的最接近成功截断正文的结果是 (n) 始终在按钮旁边右对齐,即使正文足够短以适合。这不是我想要的。
你会如何处理这个问题?
我还没有发布我当前的任何 XML,以免影响任何人的建议。
最佳答案
我不相信有任何 xml 布局。我的猜测是您需要扩展 TextView
并测量 onDraw(...)
中的文本长度,通过一些迭代相应地调整文本(即,一次删除一个字符,直到文本适合 Canvas )
我刚发现另一个与您的问题非常相似的问题:Ellipsize only a section in a TextView .除了中间的椭圆形之外没有其他答案。
另一个想法:
我想知道是否可以使用一个带主文本的 TextView (左侧椭圆、wrap_content)和另一个在括号中包含数字 (wrap_content),都在水平线性布局中。该布局将在相对布局内,layout_toLeftOf 按钮将是wrap_content、layout_alignParentRight。
这有什么意义吗?我现在没有 Eclipse 可以自己测试。不确定 (n) textview 是否会丢失在按钮后面或长文本。
或者(不太有趣),您可以使用两个 TextView 设置一个单一的相对布局 all layout_toRightOf 并且按钮右对齐(layout_alignParentRight) 并设置第一个 TextView 的最大宽度 (android:maxWidth)。 不过,您需要为不同的屏幕设置不同的布局。
一个具有固定最大宽度的示例,该示例将按要求工作:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click me"
android:id="@+id/bt1"
android:layout_alignParentRight="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="short text"
android:lines="1"
android:ellipsize="end"
android:id="@+id/t1"
android:layout_alignParentLeft="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(n)"
android:lines="1"
android:id="@+id/n1"
android:layout_toRightOf="@id/t1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click me"
android:id="@+id/bt2"
android:layout_below="@id/bt1"
android:layout_alignParentRight="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="very long text that will not fit in any layout, regardless of the size of the screen"
android:lines="1"
android:ellipsize="end"
android:id="@+id/t2"
android:layout_below="@id/bt1"
android:layout_alignParentLeft="true"
android:maxWidth="220dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(n)"
android:lines="1"
android:id="@+id/n2"
android:layout_below="@id/bt1"
android:layout_toRightOf="@id/t2"
/>
</RelativeLayout>
关于Android布局空间填充问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930930/