gpt4 book ai didi

android - 自定义 EditText 默认光标位置

转载 作者:搜寻专家 更新时间:2023-11-01 09:25:31 27 4
gpt4 key购买 nike

我有一个自定义的 EditText。它有一个不可编辑的前缀和后缀,以及一个可编辑的中间部分。问题是默认光标位置始终位于可编辑文本的开头,如下面的屏幕截图所示。

screenshot

这是我的自定义 View 的 onDraw()

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
suffixXPosition = (int) (textPaint.measureText(getText().toString()) + leftPadding + textPaint.measureText(prefix));
canvas.drawText(prefix, prefixXPosition, getBaseline(), textPaint);
canvas.drawText(getText().toString(), stringXPosition, getBaseline(), textPaint);
canvas.drawText(suffix, suffixXPosition, getBaseline(), textPaint);
}

这是非常基本的。它只是在 Canvas 上绘制文本。

我希望在呈现 EditText 时光标出现在可编辑文本的末尾我怎样才能做到这一点? 我希望 View 自己处理这种情况。

我在 onDraw 方法中尝试了 setSelection(getText().toString().length());。它在正确的位置绘制光标。但这让我无法更改触摸事件的光标位置。

最佳答案

尝试将光标位置设置在onAttachedToWindow()

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
setSelection(getText().toString().length());//set your cursor position
}

关于android - 自定义 EditText 默认光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com