Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android EditText 去邊框並自繪下劃線

編輯:關於 Android 程式設計

直接上程式碼。先在版面中把背景與文字顏色設為 @null,拿掉系統預設的邊框:

 <span ><?xml version="1.0" encoding="utf-8"?> </span> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!--注意名稱 --> <com.marine.study.LineEditText android:id="@+id/myEdit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@null" android:textColor="@null" /> </LinearLayout> 

兩點補充:background 也可以換成自訂的 drawable 或顏色;textColor 未必要設為 null,可依設計需求指定字色。注意標籤名稱要寫成完整的類別路徑,因為這是我們自訂的控制項。

自繪下劃線

接著覆寫 onDraw,用 Paint 逐行畫出底線:

 public class LineEditText extends EditText { // 畫筆 用來畫下劃線 private Paint paint; public LineEditText(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.RED); // 開啟抗鋸齒 較耗內存 paint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 得到總行數 int lineCount = getLineCount(); // 得到每行的高度 int lineHeight = getLineHeight(); // 根據行數循環畫線 for (int i = 0; i < lineCount; i++) { int lineY = (i + 1) * lineHeight; canvas.drawLine(0, lineY, this.getWidth(), lineY, paint); } } }

關鍵是 getLineCount() 與 getLineHeight():前者取得實際行數,後者取得單行高度,兩者相乘即可算出每行底線的 y 座標。這樣即使內容換行成多行,每一行都會有對應的底線,而不會只畫一條。

若想讓線條更精緻,可以再調整 paint 的 strokeWidth,或改用 drawable 搭配 selector 實作聚焦時變色。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved