在Android中,處理富文本(Rich Text)文本溢出的方法如下:
SpannableString
和ImageSpan
創建富文本:SpannableStringBuilder builder = new SpannableStringBuilder("示例文本");
ImageSpan imageSpan = new ImageSpan(getResources().getDrawable(R.drawable.ic_example));
builder.setSpan(imageSpan, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Paint paint = new Paint();
paint.setTextSize(getTextSize());
float textWidth = paint.measureText(builder.toString());
RectF rect = new RectF();
paint.getTextBounds(builder.toString(), 0, builder.length(), rect);
boolean isOverflow = textWidth > getWidth();
if (isOverflow) {
// 截斷文本
String truncatedText = builder.subSequence(0, getMaxLineCount() - 1).toString();
builder.delete(0, truncatedText.length());
// 添加省略號
SpannableString ellipsisSpan = new SpannableString("...");
ellipsisSpan.setSpan(new ForegroundColorSpan(Color.GRAY), builder.length(), builder.length() + 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append(ellipsisSpan);
}
TextView
:TextView textView = findViewById(R.id.textView);
textView.setText(builder);
請注意,這里的getMaxLineCount()
方法需要你自己實現,以確定允許的最大行數。你還可以根據需要自定義其他樣式和處理邏輯。