我有2个textview在一行和2个要求:
1)如果第一个TextView不是太宽,它应该看起来如下
|文字[1][2]文本,,,,,,,,,,,,,,,|
2)如果第一个TextView太宽,它应该看起来如下
|[1 text text tex…]文本][2]|
第二个要求很简单,你可以使用android:layout_weight="1",例如:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="end"
android:text="1 text text text text text"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2 text"
/>
</LinearLayout>
,但是如果第一个TextView包含一个短文本,它看起来像
| (1 text ,,,,,,,,,,,,,,)[2]文本|
,这是不可接受的。
那么如何同时满足1)和2)两个要求呢?
在此期间,我发现了一个非常简单的解决方案:只需将LinearLayout的宽度设置为"wrap_content"而不是"fill_parent"。
<LinearLayout
android:orientation="horizontal"
android:layout_width="WRAP_CONTENT"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="end"
android:text="1 text text text text text"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2 text"
/>
</LinearLayout>
我不认为你可以单独使用布局。为了让Android能够椭圆化Text1,它必须知道TextView
的确切宽度。你只能给它一个固定的大小或者给其他视图一个固定的大小。这两种方法你都不想做。
您需要测量每个TextView
中的文本的宽度,就好像要渲染一样。一旦你知道了每个文本的宽度,你就可以在代码中决定如何让布局达到你想要的效果。
添加另一个View
到有android:layout_weight="1000"
的LinearLayout。如果text1和text2的宽度之和不超过屏幕宽度,那么这将占用所有未使用的空间。现在计算text1和text2的宽度,如下所示:
Rect bounds = new Rect();
Paint textPaint = textView1.getPaint();
textPaint.getTextBounds(text1, 0, text1.length(), bounds);
int widthText1 = bounds.width();
textPaint = textView2.getPaint();
textPaint.getTextBounds(text2, 0, text2.length(), bounds);
int widthText2 = bounds.width();
现在你知道了text1和text2在完全渲染后需要的宽度。
if (widthText1 + widthText2 > screenWidth) {
View3.setVisibility(View.GONE); // Don't need View3 as there is no extra space
}
在一种情况下,View3将占用所有剩余空间。在另一种情况下,TextView1应该在末尾被省略。
我实际上并没有测试过这个,所以如果它不起作用,请不要对我太苛刻。