頁簽/標題下方有一條底線,寬度需與文字內容等寬,文字變化時底線跟隨調整。
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="標題" />
<View
android:layout_width="match_parent" // 關鍵:父容器 wrap_content,此處 match_parent 即文字寬
android:layout_height="2dp"
android:background="#FF0000" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="標題"
android:drawableBottom="@drawable/underline_9patch"
android:drawablePadding="4dp" />
underline_9patch.9.png:中間 1px 可拉伸,左右固定,高度 2px。
public class UnderlineTextView extends AppCompatTextView {
private Paint _underlinePaint = new Paint();
private int _underlineHeight = 4;
private int _underlineColor = Color.RED;
public UnderlineTextView(Context context, AttributeSet attrs) {
super(context, attrs);
_underlinePaint.setColor(_underlineColor);
_underlinePaint.setStrokeWidth(_underlineHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 獲取文字實際寬度
float textWidth = getPaint().measureText(getText().toString());
float x = (getWidth() - textWidth) / 2f; // 居中
float y = getHeight() - getPaddingBottom();
canvas.drawLine(x, y, x + textWidth, y, _underlinePaint);
}
}
XML 中直接用 <com.example.UnderlineTextView .../>。
| 方案 | 優點 | 缺點 |
|---|---|---|
| wrap_content View | 零代碼,純 XML | 需額外父容器,動畫稍繁瑣 |
| drawableBottom | 複用性強,支持圖片漸變 | 需製作 9-patch,padding 調試麻煩 |
| 自定義 View | 完全可控,支持動畫/虛線/顏色漸變 | 代碼量最多 |