自定义EditText不显示上面的行

时间:2016-09-18 11:22:24

标签: android android-edittext android-custom-view

我正在构建一个来自this answer的自定义EditText,这是我得到的输出,

enter image description here 问题 线条没有从顶部开始,它们从中间的某个地方开始,可能是错误的。

这是代码,

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);
    }
}

这是我的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>

1 个答案:

答案 0 :(得分:0)

我所做的只是增加了重力,一切都很好,

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