2

我有一个 TextView,最多应该有 15 个字符,最后应该有三个点。使用我的 XML,它会减少 15 个字符,但不会...在末尾添加三个点。

重要提示:我知道当我用行数限制文本时它会起作用 - android:maxLines="2"。但我需要用最大字符数来限制它,如问题所述。

<TextView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:maxLength="15"
    android:ellipsize="end"
    tools:text="123456789qwertyuiopasdfghjklzxcvbnm"
    android:textSize="50sp"
/>

结果:

在此处输入图像描述

4

2 回答 2

5

我不确定如何或是否可以在 XML 中做你想做的事。

至少我不知道如何 - 但我有一个替代解决方案给你。

public void ellipsizeText(TextView tv){
    int maxLength = 13;
    if(tv.getText().length() > maxLength){
        String currentText = tv.getText().toString();
        String ellipsizedText =  currentText.substring(0, maxLength - 3) + "...";
        tv.setText(ellipsizedText);
    }
}

所以我只是把它作为一个以文本视图作为参数的方法。这真的很简单,您将 maxLength 更改为所需的字符串最大长度。在这种情况下,它设置为 13,因为它将最后 3 个字符替换为“...”,然后生成一个仍然 13 个字符长的字符串,但前 10 个是实际文本,最后 3 个是“ ……”。

在您的主项目中,您可以将 maxLength 更改为 150(或 153,如果您想要字符串中的 150 个可见字符)

希望您可以使用它,如果您有任何问题,请告诉我。

于 2018-01-17T12:43:38.503 回答
1

试试这个解决方案:

 <TextView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:ellipsize="end"
    android:singleLine="true"
    android:maxLines="1"
    android:text="123456789qwertyuiopasdfghjklzxcvbnm"
    android:textSize="50sp"
    />

希望这对你有帮助......如果你需要任何帮助,你可以问

于 2018-01-17T12:05:23.843 回答