Android Sample NotePad学习三

本文介绍了一个自定义的EditText控件,该控件能在每行文本下方自动绘制一条横线,适用于日记等应用场景。通过重写onDraw()方法实现,并详细解释了getLineCount()及getLineBounds(int line, Rect bounds)等关键方法的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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就可以只不过每写一行在下面加一个横线

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值