在NotePad中当我们编辑一片日记的时候每次按回车就会出现在下面出现一个横线,学习一下对于以后自定义控件提供一点思路,看一下效果如下:
/** * A custom EditText that draws lines between each line of text that is displayed. */ public static class LinedEditText extends EditText { private Rect mRect; private Paint mPaint; // we need this constructor for LayoutInflater public LinedEditText(Context context, AttributeSet attrs) { super(context, attrs); mRect = new Rect(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x800000FF); } @Override protected void onDraw(Canvas canvas) { int count = getLineCount(); Rect r = mRect; Paint paint = mPaint; for (int i = 0; i < count; i++) { int baseline = getLineBounds(i, r); canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); } super.onDraw(canvas); } }
因为这个控件艾女士继承自TextView的,所以他有TextView的方法,其实这个的原理就是当我们在上面写的时候其实是不停地onDraw()的,然后重写这个方法,然后在上面每一行加了一条横线,
对于getLineCount()的解释
Return the number of lines of text, or 0 if the internal Layout has not been built.
对于getLineBounds(int line,Rect bounds)的解释:
Return the baseline for the specified line (0...getLineCount() - 1) If bounds is not null, return the top, left, right, bottom extents of the specified line in it. If the internal Layout has not been built, return 0 and set bounds to (0, 0, 0, 0)
- Parameters:
- line which line to examine (0..getLineCount() - 1)
- bounds Optional. If not null, it returns the extent of the line Returns:
- the Y-coordinate of the baseline
- 可以看出返回的是当前行的左上角的y坐标的值
note_editor.xml
<view xmlns:android="http://schemas.android.com/apk/res/android" class="com.example.android.notepad.NoteEditor$LinedEditText" android:id="@+id/note" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent" android:padding="5dip" android:scrollbars="vertical" android:fadingEdge="vertical" android:gravity="top" android:textSize="22sp" android:capitalize="sentences" />
在xml文件中引用自定义的空间,其实就当成TextView就可以只不过每写一行在下面加一个横线