首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TextView 底部下劃線寬度自適應文字內容的實現

     編輯:程式設計綜合問答

需求

頁簽/標題下方有一條底線,寬度需與文字內容等寬,文字變化時底線跟隨調整。

方案一:wrap_content View(最簡單)

<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>

方案二:drawableBottom 九宮格圖片

<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。

方案三:自定義 View 繪製(完全控制)

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完全可控,支持動畫/虛線/顏色漸變代碼量最多
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved