pcpriyanka pcpriyanka - 1 month ago 7
Android Question

Add horizontal line inside EditText

I have created one

EditText
programatically when I type in
EditText
if the text goes to next line then I want to draw horizontal line inside
EditText
. How can I achieve it ?

Answer

As per the Raghunandan comment, You can use this class in your project

LinedEditText.java

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

public class LinedEditText extends EditText {
    private Paint mPaint = new Paint();

    public LinedEditText(Context context) {
        super(context);
        initPaint();
    }

    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public LinedEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initPaint();
    }

    private void initPaint() {
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0x80000000);
    }

    @Override protected void onDraw(Canvas canvas) {
        int left = getLeft();
        int right = getRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int height = getHeight();
        int lineHeight = getLineHeight();
        int count = (height-paddingTop-paddingBottom) / lineHeight;

        for (int i = 0; i < count; i++) {
            int baseline = lineHeight * (i+1) + paddingTop;
            canvas.drawLine(left+paddingLeft, baseline, right-paddingRight, baseline, mPaint);
        }

        super.onDraw(canvas);
    }
} 

use it in layout file

   <yourpackagename.LinedEditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/transparent"
            android:ems="10"
            android:gravity="top"
            android:hint="@string/note_body"
            android:inputType="textMultiLine"
            android:lineSpacingExtra="4dp"
            android:textColor="#000000"
            android:textColorHint="#e2e2e2" />
Comments