TextView折疊展示一段文字
效果圖
展開前

展開后

public class TextViewLinesUtils {
/**
* 設定textView結尾...后面顯示的文字和顏色
* @param context 背景關系
* @param textView textview
* @param minLines 最少的行數
* @param originText 原文本
* @param endText 結尾文字
* @param endColorID 結尾文字顏色id
* @param isExpand 當前是否是展開狀態
*
* 這個方法如果放在RecycleView里面的話,會有復用問題導致不顯示,所以不能在Recyclerview里面用這個方法
*/
public static void toggleEllipsize(final Context context, 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;
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);
}
}
});
}
}
使用注意一點
endText前面加兩個…,
tv_desc.setOnClickListener {
if (isExpand){
isExpand = false
tv_desc.maxLines = 2
}else{
isExpand = true
tv_desc.maxLines = Int.MAX_VALUE
}
TextViewLinesUtils.toggleEllipsize(
activity, tv_desc, 2, "香港在全球金融中心指數上一直名列為全球第三大金融中心香港在全球金融中心指數上一直名列為全球第三大金融中心,連續第20年獲得全球最自由經濟體系評級,經濟自由度指數排名第一,",
"..展開全部",
R.color.ec_text_333333, isExpand
)
}
TextViewLinesUtils.toggleEllipsize(
activity, tv_desc, 2, "香港在全球金融中心指數上一直名列為全球第三大金融中心香港在全球金融中心指數上一直名列為全球第三大金融中心,連續第20年獲得全球最自由經濟體系評級,經濟自由度指數排名第一,",
"..展開全部",
R.color.ec_text_333333, isExpand
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/218833.html
標籤:AI
