自定义Edittext使用onDraw和光标位置不匹配?

时间:2013-11-21 06:34:39

标签: android android-edittext

我正在制作自定义的Edittext。这是代码: -

package com.wysiwyg.main;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;

public class LineEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;

    // we need this constructor for LayoutInflater
    public LineEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setColor(Color.BLUE); //SET YOUR OWN COLOR HERE
        setMinLines(15);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int height = getHeight();
        int line_height = getLineHeight();

        int count = height / line_height;
        if(getLineCount() > count){
            count = getLineCount();
        }
        Rect r = mRect;
        Paint paint = mPaint;
        int baseline = getLineBounds(0, r);

        for (int i = 0; i < count; i++) {

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
            baseline += getLineHeight()+10;//next line
        }

        // Finishes up by calling the parent method
        super.onDraw(canvas);
    }
}

现在这一行baseline += getLineHeight()+10;//next line在线上方的特定空间绘制下一行。现在光标位置不会相对于线移动。如果我按回车键,则光标首先出现在线上方,然后我按下回车键,它就会出现在行之间。

我希望你能理解我的意思。

1 个答案:

答案 0 :(得分:0)

试试这种方式

public class MyEditText extends EditText {


    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyEditText(Context context) {
        super(context);
        init(context);
    }

    private void init(Context mContext) {
        setLineSpacing(2, 1); // You can set here as your requirement
    }


}