4

我连续有 2 个 TextViews 和 2 个要求:

1) 如果第一个 TextView 不是太宽,应该如下所示

|[1 条文字][2 条文字] |

2) 如果第一个 TextView 太宽,应该如下所示

|[1 个文本文本 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 条文字][2 条文字]|

,这是不可接受的。

那么如何同时满足1)和2)的要求呢?

4

2 回答 2

8

与此同时,我找到了一个非常简单的解决方案:只需将 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>
于 2013-05-16T00:43:10.207 回答
1

我不认为你可以单独使用布局来做到这一点。为了让 Android 能够省略 Text1,它必须知道TextView. 您只能通过给它一个固定大小或给其他视图固定大小来做到这一点。你不想做这些。

您需要测量每个文本的宽度,TextView 就好像它要被渲染一样。一旦您知道每个文本将占用的宽度,您就可以在代码中决定如何让布局执行您想要的操作。

将另一个添加View到具有android:layout_weight="1000". 如果 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 最后应该是椭圆形的。

我实际上并没有对此进行测试,所以如果它不起作用,请不要对我太苛刻。

于 2013-05-15T21:29:27.217 回答