在EditText

时间:2016-10-21 06:32:21

标签: android android-edittext horizontal-line

如果文字转到下一行,我输入EditText时会以编程方式创建一个EditText,然后我想在EditText内绘制水平线。我怎样才能实现它?

1 个答案:

答案 0 :(得分:2)

根据Raghunandan评论,您可以在项目中使用此类

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

在布局文件中使用它

   <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" />