Android:将文本插入到当前位置的EditText中
我想通过按按钮将常量字符串插入 EditText 中。该字符串应插入到 EditText 中的当前位置。 如果我使用 EditText.append
文本将插入到 EditText 的末尾。
我怎样才能做到这一点?我找不到合适的方法。
I want to insert a constant string into an EditText by the press of a button. The string should be inserted at the current position in the EditText.
If I use EditText.append
the text gets inserted at the end of the EditText.
How can I do that? I couldn't find a suitable method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
奥伦德上尉给了我正确的提示。我现在部分地使用
EditText.getSelectionStart()
解决了这个问题,但我意识到您也可以用相同的表达式替换所选文本,并且不需要String.subString( )
为此。这适用于两者,在当前位置插入文本并替换用户选择的任何文本。 Math.max() 在第一行和第二行中是必需的,因为如果 EditText 中没有选择或光标,则 getSelectionStart() 和 getSelectionEnd( ) 都会返回 -1。第三行中的
Math.min()
和Math.max()
是必需的,因为用户可能向后选择文本,因此 start 的值会高于Editable.replace()
不允许使用 end 。Cpt.Ohlund gave me the right hint. I solved it, now, partly with using
EditText.getSelectionStart()
, but I realized that you can also replace the selected text with the same expression and you don't needString.subString()
for that.This works for both, inserting a text at the current position and replacing whatever text is selected by the user. The
Math.max()
is necessary in the first and second line because, if there is no selection or cursor in the EditText,getSelectionStart()
andgetSelectionEnd()
will both return -1. TheMath.min()
andMath.max()
in the third line is necessary because the user could have selected the text backwards and thus start would have a higher value than end which is not allowed forEditable.replace()
.这看起来更简单:
但是,如果您想用插入的文本替换任何选定的文本,曼努埃尔的答案可能会更好。
This seems simpler:
However, Manuel's answer might be better if you want to replace any selected text with the inserted text.
尝试使用
EditText.getSelectionStart()
获取光标的当前位置。然后,您可以使用 String.subString 获取光标之前和之后的文本,并将文本插入到中间。Try using
EditText.getSelectionStart()
to get the current position of the cursor. Then you can use String.subString to get the text before and after the cursor and insert your text in the middle.对于 Kotlin 只需这样做:
For Kotlin simply do that:
我认为这个功能会对你有所帮助:
I think this function will help for you :
Editable editable = new SpannableStringBuilder("在此处传递一个字符串");
yourEditText.text = 可编辑;
Editable editable = new SpannableStringBuilder("Pass a string here");
yourEditText.text = editable;