自定义view(使用EditTetx实现记事本特效)

时间:2021-10-23 17:24:18

先看一下效果图:

自定义view(使用EditTetx实现记事本特效)

思路: 创建一个类,继承自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); } @Override
protected 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>