user6761472 user6761472 - 3 months ago 27
Android Question

How to set line for EditText in Android

I want develop notepad app, and I wan to set line for my

EditText
, such as below image :

enter image description here


But I don't know how can I create this? please help me in creating this design.
Thanks all.

Answer

Try this code :

Create Java class and copy below codes into that

/**
 * Created by Mohammad.N on 28/08/2016.
 */
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;

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

    public LinedEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0xFF000000);
    }

    /**
     * This is called to draw the LinedEditText object
     * @param canvas The canvas on which the background is drawn.
     */
    @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();

            super.onDraw(canvas);
        }
    }
}

Then, user this EditText into your XML file

<com.mohammad.nouri.diaryday.Components.LinedEditText
    android:id ="@+id/edtInput"
    android:layout_width ="match_parent"
    android:layout_height ="wrap_content"
    android:layout_below="@id/main_toolbar"
    android:hint ="insert text" />

I hope help you my friend

Comments