Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText line spacing increase issue and cursor position w.r.t line

I am trying to create an EditText such that the space between each line should be like 20 dp. Please see the image below.

If I use line spacing extra, then the cursor position is not correctly aligned with the line. I have achieved the line spacing, but the cursor is not aligned with the line. See the red box highlighted in the image below.

package com.example.dev_task_197_keyboard_accesory;

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();//next line
        }

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

For line spacing, add lineSpaceExtra and lineSpaceMultiplier parameter in the xml.

Please suggest.

enter image description here

like image 759
Rahul Gupta Avatar asked Nov 18 '13 07:11

Rahul Gupta


1 Answers

Two possible options for resolving your problem can be found here. I tested the first one (only works on API 12+), it worked for me.

like image 50
Onik Avatar answered Nov 12 '22 06:11

Onik