設置 android:maxLines="2" 和 android:ellipsize="middle",期望超出兩行時在中間顯示「...」,但實際顯示為兩行完整文本,**無省略號**,且文本被截斷。
android:ellipsize="middle" **僅對單行文本生效**。多行文本下,Android 框架**不支援中間省略**,僅支援 end (結尾省略) 和 marquee (跑馬燈)。
效果:顯示前兩行內容,超出部分在**第二行末尾**顯示「...」。
若業務強制要求中間省略或「查看更多」交互,需自定義實現:
onMeasure、onDraw,使用 StaticLayout 測量文本行數。ExpandableTextView、ReadMoreTextView。
代碼邏輯:
TextView tvContent = findViewById(R.id.tv_content);
TextView tvMore = findViewById(R.id.tv_more);
tvContent.post(() -> {
Layout layout = tvContent.getLayout();
if (layout != null && layout.getLineCount() > 2) {
tvMore.setVisibility(View.VISIBLE);
tvMore.setOnClickListener(v -> {
if (tvContent.getMaxLines() == 2) {
tvContent.setMaxLines(Integer.MAX_VALUE);
tvMore.setText("收起");
} else {
tvContent.setMaxLines(2);
tvMore.setText("展開");
}
});
}
});
| ellipsize 值 | 單行 | 多行 (maxLines > 1) | 說明 |
|---|---|---|---|
start | ✅ | ❌ 無效果 | 開頭省略 |
middle | ✅ | ❌ 無效果 | 中間省略 |
end | ✅ | ✅ **支援** | 結尾省略 (多行推薦) |
marquee | ✅ | ❌ 需單行+focus | 跑馬燈滾動 |
none | ✅ | ✅ | 不省略,直接截斷 |
ellipsize="end"** 顯示省略號。android:maxLines 時務必搭配 ellipsize,否則超出部分直接截斷無提示。