Weird Nerd Weird Nerd - 2 months ago 12
Android Question

Custom EditText does not show lines above

I am building a custom EditText from this answer, this is the output I am getting,

enter image description here
Problem
The lines are not starting right at the top,they are starting somewhere in the middle, what could be wrong.

Here is the code,

public class LinedEditText extends EditText {

private static Paint linePaint;

static {
linePaint = new Paint();
linePaint.setColor(Color.BLACK);
linePaint.setStyle(Paint.Style.STROKE);
}

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

@Override
protected void onDraw(Canvas canvas) {
Rect bounds = new Rect();
int firstLineY = getLineBounds(0, bounds);
int lineHeight = getLineHeight();
int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);

for (int i = 0; i < totalLines; i++) {
int lineY = firstLineY + i * lineHeight;
canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint);
}

super.onDraw(canvas);
}
}


Here is my XML,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/PeachPuff"
>

<TextView
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:padding="8dp"
android:layout_margin="10dp"
android:background="@drawable/shape"
android:layout_gravity="center_horizontal" />



<com.random.simplenotes.LinedEditText
android:layout_width="match_parent"
android:layout_height="match_parent"

/>


</LinearLayout>

Answer

All I did was added the gravity and everything was fine,

<com.random.simplenotes.LinedEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="textMultiLine"
        android:gravity="top|left"
        />