標籤:
先看一下:
思路: 建立一個類,繼承自EditText,在onDraw方法中繪製我們的底線,通過螢幕的高度和每行控制項的高度的比值得出螢幕中應該繪製多少行底線,再來實現一些自訂的屬性,設定控制項基本的邊距和內容邊距就ok了 ,過程很簡單的,代碼的注釋寫的很詳細,有需要的同學可以去閱讀一下
自訂類MyNoteEditText.class
package com.wjt.day43_01_mynoteedittext;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.Gravity;import android.widget.EditText;public class MyNoteEditText extends EditText{ private int lineColor = Color.RED ; private int lineStrokWidth = 1 ; private int padding = 10 ;public MyNoteEditText(Context context, AttributeSet attrs) {super(context, attrs);//這句話是讓每一行的輸入的資料都位於他的左上部分setGravity(Gravity.TOP);TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyNoteEditText);lineColor = array.getColor(R.styleable.MyNoteEditText_lineColor, lineColor);lineStrokWidth = (int) array.getDimension(R.styleable.MyNoteEditText_lineStrokWidth, lineStrokWidth);padding = (int) array.getDimension(R.styleable.MyNoteEditText_padding, padding);array.recycle();//實現內容和劃線部分的一一對應setPadding(padding, 0, padding, 0);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//1,建立一個畫筆Paint paint = new Paint();paint.setAntiAlias(true);paint.setColor(lineColor);paint.setStrokeWidth(lineStrokWidth);//2,擷取當前整個控制項的寬高 int viewHeight = getHeight();int viewWidth = getWidth() ;//3,擷取EditText中每一行的寬度int lineHeight = getLineHeight();//4,通過計算螢幕中一共能放多少行int pageLineCounts = viewHeight/lineHeight ;//5,使用畫布劃線for (int i = 0; i < pageLineCounts; i++) {canvas.drawLine(padding, (i+1)*lineHeight, viewHeight - padding, (i+1)*lineHeight, paint);}//6,實現當文字寫到下一頁的時候繼續劃線int textLineCount =getLineCount() ; if (textLineCount > pageLineCounts) {for (int i = pageLineCounts; i < textLineCount; i++) {canvas.drawLine(padding, (i+1)*lineHeight, viewHeight - padding, (i+1)*lineHeight, paint);}}}}
自訂屬性部分attrs.xml
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name = "NoteEditText"> <attr name = "lineColor" format="color|reference"/> <attr name = "lineStrokeWidth" format="dimension|reference"/> <attr name = "padding" format="dimension|reference"/> </declare-styleable></resources>
自訂view(使用EditTetx實現記事本特效)