使用Spannable的TextView-ellipsize不起作用 [英] TextView using Spannable - ellipsize doesn't work
问题描述
我要解决的问题如下:我正在使用TextView
,并且正在使用Spannable
将某些字符设置为粗体.
文本的最大长度为2行(android:maxLines="2"
),我希望将文本椭圆化,但是由于某种原因,我无法使文本变为椭圆形.
The issue I'm trying to fix is the following: I'm having a TextView
and I'm using a Spannable
to set some characters bold.
The text needs to have a maxim of 2 lines ( android:maxLines="2"
) and I want the text to be ellipsized, but for some reason I cannot make the text ellipsized.
这是简单的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="2"
android:ellipsize="end"
android:bufferType="spannable"
android:text="@string/app_name"
android:textSize="15dp"/>
</LinearLayout>
和活动:
public class MyActivity extends Activity {
private TextView name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name= (TextView) findViewById(R.id.name);
name.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy ");
Spannable spannable = (Spannable)name.getText();
StyleSpan boldSpan = new StyleSpan( Typeface.BOLD );
spannable.setSpan( boldSpan, 10, 15, Spannable.SPAN_INCLUSIVE_INCLUSIVE );
}
}
文本被截断,不显示"...".
The text is truncated, no "..." are displayed.
推荐答案
我意识到这是一篇很老的文章,但是由于仍然没有答案,所以我今天也遇到了这个问题,我想我应该发布一个解决方案.希望它对将来的人有所帮助.
I realise this is a very old post, but seeing as it's still unanswered and I also ran into this issue today I thought I would post a solution to this. Hopefully it helps someone in the future.
ViewTreeObserver viewTreeObserver = textView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
ViewTreeObserver viewTreeObserver = textView.getViewTreeObserver();
viewTreeObserver.removeOnGlobalLayoutListener(this);
if (textView.getLineCount() > 5)
{
int endOfLastLine = textView.getLayout().getLineEnd(4);
String newVal = textView.getText().subSequence(0, endOfLastLine - 3) + "...";
textView.setText(newVal);
}
}
});
这篇关于使用Spannable的TextView-ellipsize不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!