Android: TextView 会自动截断并替换最后3个字符串

如果 String长于 TextView的宽度,它会自动换行到下一行。我可以通过使用 android:singleLine(不推荐)或设置 android:inputType="text"来避免这种情况。我现在需要的是一些东西,取代我的 String的最后3个字符与“ ...”。由于我没有使用单一空间字体,这将始终是不同的,这取决于我的 String中使用的字母。所以我想知道什么是最好的方法来获得一个字符串的最后3个字符在 TextView和替换他们。也许 Android 框架中已经实现了一些东西,因为这肯定是一个常见的问题。

101184 次浏览

您应该能够使用文本视图的“椭圆大小”属性:

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_mytext"
android:ellipsize="end"
android:maxLines="1"
/>

您可能还需要对布局应用重力值; 我有时看到“自动拉伸”视图没有重力值。

为这个问题找到了一个有趣的解决办法。

maxLines=1
ellipsize=end
scrollHorizontally=true

诀窍在于最后一个关于水平滚动的声明... ... 看看吧。它至少在 v2.2上有效。

通过编程,您可以使用:

TextView tx = new TextView(this);
tx.setTextSize(13);
tx.setGravity(Gravity.CENTER);
tx.setTop(90);
tx.setText("Long text here");
tx.setTextColor(Color.BLACK);
tx.setSingleLine(true);
tx.setEllipsize(TruncateAt.END);

只要加上 关于 XML 的 android:ellipsize="end" 你的代码应该是这样的

<TextView
android:id="@+id/newsTitleTextView"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@id/newsThumbnailImageView"
android:ellipsize="end"
android:maxLines="2"
android:text="Analysts See Slower Bitcoin Hashrate Growth in 2022 Amid Market Correction "
android:textSize="15sp" />