如何将Android截断的文本转换为省略号?
我有一个textview:
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:text="Um longo texto aqui de exemplo" />
在设备上,此TextView显示如下:
"Um longo texto a..."
如何获取其余文本?
我正在寻找像getRestOfTruncate()
这样会返回“qui de exemplo”的东西。
答案 0 :(得分:7)
String text = (String) textView.getText().subSequence(textView.getLayout().getEllipsisStart(0), textView.getText().length());
答案 1 :(得分:0)
使用textView.getLayout()。getEllipsisStart(0)仅在android:singleLine =&#34; true&#34;
时有效如果设置了android:maxLines,这个解决方案将起作用:
public static String getEllipsisText(TextView textView) {
// test that we have a textview and it has text
if (textView==null || TextUtils.isEmpty(textView.getText())) return null;
Layout l = textView.getLayout();
if (l!=null) {
// find the last visible position
int end = l.getLineEnd(textView.getMaxLines()-1);
// get only the text after that position
return textView.getText().toString().substring(end);
}
return null;
}
请记住:这在视图已经可见后才有效。
<强>用法:强>
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Log.i("test" ,"EllipsisText="+getEllipsisText(textView));
}
});
答案 2 :(得分:0)
我的解决方案。 Kotlin扩展功能:
fun TextView.getEllipsizedText(): String {
if (text.isNullOrEmpty()) return ""
return layout?.let {
val end = textContent.text.length - textContent.layout.getEllipsisCount(maxLines - 1)
return text.toString().substring(0, end)
} ?: ""
}