有2中方法
- //中畫線
- textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 設置中劃線並加清晰
- //下劃線
- textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
- //取消設置的線
- textView.getPaint().setFlags(0);
- //抗鋸齒
- textView.getPaint().setAntiAlias(true);
自定義下劃線UnderlineTextView
public class UnderlineTextView extends android.support.v7.widget.AppCompatTextView {
//Paint即畫筆,在繪圖過程中起到了極其重要的作用,畫筆主要保存了顏色,
//樣式等繪製信息,指定了如何繪製文本和圖形,畫筆對象有很多設置方法,
//大體上可以分爲兩類,一類與圖形繪製相關,一類與文本繪製相關
private final Paint paint = new Paint();
//下劃線高度
private int underlineHeight = 0;
//下劃線顏色
private int underLineColor;
//通過new創建實例是調用這個構造函數
//這種情況下需要添加額外的一些函數供外部來控制屬性,如set*(...);
public UnderlineTextView(Context context) {
this(context, null);
}
//通過XML配置但不定義style時會調用這個函數
public UnderlineTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
//獲取自定義屬性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UnderlineTextView);
//獲取具體屬性值
underLineColor = typedArray.getColor(R.styleable.UnderlineTextView_underline_color, getTextColors().getDefaultColor());
underlineHeight = (int) typedArray.getDimension(R.styleable.UnderlineTextView_underline_height,
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
}
//通過XML配置且定義樣式時會調用這個函數
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
//防止下劃線高度大到一定值時會覆蓋掉文字,需從寫此方法
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom + underlineHeight);
}
//繪製下劃線
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//設置下劃線顏色
paint.setColor(underLineColor);
//float left, float top, float right, float bottom
canvas.drawRect(0, getHeight() - underlineHeight, getWidth(), getHeight(), paint);
}
}
style 裏面
<!-- UnderlineTextView -->
<declare-styleable name="UnderlineTextView">
<attr name="underline_color" format="color"/>
<attr name="underline_height" format="dimension"/>
</declare-styleable>
xml使用
聲明命名空間 xmlns:app="http://schemas.android.com/apk/res-auto"
<xxx.UnderlineTextView
android:id="@+id/tv_forget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorPrimary"
app:underline_color="@color/colorPrimary"
app:underline_height="1dp" />
效果圖