Fre*_*ook 69 android ellipsis textview
我有一个TextView
已android:ellipsize="end"
设置的多行.但是,我想知道,如果我放在那里的字符串实际上太长了(这样我可以确保完整的字符串显示在页面的其他地方).
我可以使用TextView.length()
并找到字符串的大致长度适合的内容,但由于它是多行,TextView
句柄何时换行,所以这并不总是有效.
有任何想法吗?
Tho*_*nvv 115
您可以获取该布局TextView
并检查每行的省略号计数.对于结束省略号,检查最后一行就足够了,如下所示:
Layout l = textview.getLayout();
if (l != null) {
int lines = l.getLineCount();
if (lines > 0)
if (l.getEllipsisCount(lines-1) > 0)
Log.d(TAG, "Text is ellipsized");
}
Run Code Online (Sandbox Code Playgroud)
这仅在布局阶段之后有效,否则返回的布局将为null,因此请在代码中的适当位置调用此布局.
Him*_*ani 31
textView.getLayout是要走的路,但问题是如果没有准备布局,它会返回null.使用以下解决方案.
ViewTreeObserver vto = textview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Layout l = textview.getLayout();
if ( l != null){
int lines = l.getLineCount();
if ( lines > 0)
if ( l.getEllipsisCount(lines-1) > 0)
Log.d(TAG, "Text is ellipsized");
}
}
});
Run Code Online (Sandbox Code Playgroud)
Fra*_*rio 21
我认为这个问题的最简单的解决方案是以下代码:
String text = "some looooong text";
textView.setText(text);
boolean isEllipsize = !((textView.getLayout().getText().toString()).equalsIgnoreCase(text));
Run Code Online (Sandbox Code Playgroud)
此代码假定在您的XML中TextView设置了一个maxLineCount
:)
我发现(在 Kotlin 中)最雄辩的解决方案是创建一个扩展函数TextView
fun TextView.isEllipsized() = layout.text.toString() != text.toString()
Run Code Online (Sandbox Code Playgroud)
这很棒,因为它不需要知道完整的字符串是什么,也不需要担心正在TextView
使用多少行。
TextView.text
是它试图显示的全文,而TextView.layout.text
是屏幕上实际显示的内容,因此如果它们不同,则一定会被省略
使用方法:
if (my_text_view.isEllipsized()) {
...
}
Run Code Online (Sandbox Code Playgroud)
public int getEllipsisCount (int line) :
返回要被省略掉的字符数,如果没有省略号,则返回 0。
所以,只需调用:
int lineCount = textview1.getLineCount();
if(textview1.getLayout().getEllipsisCount(lineCount) > 0) {
// Do anything here..
}
Run Code Online (Sandbox Code Playgroud)
由于在设置布局之前无法调用 getLayout(),请使用以下命令:
ViewTreeObserver vto = textview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Layout l = textview.getLayout();
if ( l != null){
int lines = l.getLineCount();
if ( lines > 0)
if ( l.getEllipsisCount(lines-1) > 0)
Log.d(TAG, "Text is ellipsized");
}
}
});
Run Code Online (Sandbox Code Playgroud)
最后不要忘记在您不再需要时删除removeOnGlobalLayoutListener。
这对我有用:
textView.post(new Runnable() {
@Override
public void run() {
if (textView.getLineCount() > 1) {
//do something
}
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28170 次 |
最近记录: |