Android:TextView显示3行,超出显示...+全文, 直接上代码:
工具类:TextViewSpanUtil
public class TextViewSpanUtil { /** * 设置textView结尾...后面显示的文字和颜色 * * @param context 上下文 * @param textView textview * @param minLines 最少的行数 * @param originText 原文本 * @param endText 结尾文字 * @param endColorID 结尾文字颜色id * @param isExpand 当前是否是展开状态 */ public static void toggleEllipsize(final Context context, final TextView textView, final int minLines, final String originText, final String endText, final int endColorID, final boolean isExpand) { if (TextUtils.isEmpty(originText)) { return; } textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver .OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (isExpand) { textView.setText(originText); } else { int paddingLeft = textView.getPaddingLeft(); int paddingRight = textView.getPaddingRight(); TextPaint paint = textView.getPaint(); float moreText = textView.getTextSize() * endText.length(); float availableTextWidth = (textView.getWidth() - paddingLeft - paddingRight) * minLines - moreText - 20; CharSequence ellipsizeStr = TextUtils.ellipsize(originText, paint, availableTextWidth, TextUtils.TruncateAt.END); if (ellipsizeStr.length() < originText.length()) { CharSequence temp = ellipsizeStr + endText; SpannableStringBuilder ssb = new SpannableStringBuilder(temp); ssb.setSpan(new ForegroundColorSpan(context.getResources().getColor (endColorID)), temp.length() - endText.length(), temp.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); textView.setText(ssb); } else { textView.setText(originText); } } if (Build.VERSION.SDK_INT >= 16) { textView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { textView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); } }
使用方法:
TextView textView = findViewById(R.id.tv_text); String text = "超过3行时就在第三行的末尾显示省略号加最近有个需求就是文字显示指定行数比如3行," + "超过3行时就在第三行的末尾显示省略号加最近有个需求就是文字显示指定行数比如3行,超过3行时就在第三行的末尾显示省略号加哈哈哈哈"; TextViewSpanUtil.toggleEllipsize(context, textView, 3, text, "全文", R.color.allText, isExpandDescripe[0]); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isExpandDescripe[0]) { isExpandDescripe[0] = false; textView.setMaxLines(3);// 收起 } else { isExpandDescripe[0] = true; textView.setMaxLines(Integer.MAX_VALUE);// 展开 } TextViewSpanUtil.toggleEllipsize(context, textView, 3, text, "全文", R.color.allText, isExpandDescripe[0]); } });
Android:TextView显示3行,超出显示...+全文, 直接上代码: