增加高度时光标停留在编辑文本的中心

Cursor stays in the centre of edittext when increasing height

我正在尝试制作自定义编辑文本:

public class HeadedTintEditText extends EditText {

private String headerText;
private int headerSelectedColor;
private float headerTextSize;
private Paint textPaint;
private int textColor;

public HeadedTintEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.HeadedTintEditText, 0, 0);
    try {
        headerText = a.getString(R.styleable.HeadedTintEditText_headerText);
        headerSelectedColor = a.getColor(R.styleable.HeadedTintEditText_headerTextSelectedColor, Color.BLACK);
        textColor = a.getColor(R.styleable.HeadedTintEditText_headerTextColor, Color.BLACK);
        headerTextSize = a.getDimension(R.styleable.HeadedTintEditText_headerTextSize, 30);
    } finally {
        a.recycle();
    }
    init();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
    int w = resolveSizeAndState(minw, widthMeasureSpec, 1);
    int minh = (int) (3 * headerTextSize) + getPaddingBottom() + getPaddingTop() + getSuggestedMinimumHeight();
    int h = resolveSizeAndState(minh, heightMeasureSpec, 0);
    setMeasuredDimension(w, h);
}

@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect);
    if (focused) {
        textPaint.setColor(headerSelectedColor);
    } else {
        textPaint.setColor(textColor);
    }
}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawText(headerText, 0, headerTextSize, textPaint);
}

private void init() {
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(textColor);
    textPaint.setTextSize(headerTextSize);
}
}

一切看起来都很好,但是当我在 onMeasure 方法中增加编辑文本的高度时,光标停留在编辑文本的中心。

也许有人已经知道如何解决这个问题。我认为这是因为当 edittext 高度增加并且光标保持在原位时背景正在下降。我想我可以通过更改背景或创建可绘制的自定义光标来解决此问题。

提前致谢!

Picture of the cursor in the center

请尝试设置编辑文本的重力(和输入类型):

代码:

editText.setGravity(Gravity.BOTTOM);
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);

XML:

android:gravity="bottom"
android:inputType="textMultiLine"