安卓EditText插入文本

6
如何在EditText字段中间插入字符?
我正在制作一个可以接受字符串表达式(例如“3 *(10 ^ 2-8)”)的计算器。 我使用类似以下XML的EditText字段来创建字符串: < EditText >
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"
android:text="@string/testString1"
android:background="@android:drawable/editbox_background"

然后在我的活动中,我有如下代码:

entry = (EditText)findViewById(R.id.entry);
entry.setText("blablahblah");
entry.setSelection(3);

现在我有一个EditText字段,光标在字符串的第三个字符后闪烁。我该如何在那里插入一个字符,以便它正确地显示为“blahblahblah”?

2个回答

4
EditText小部件的getText()方法返回一个实现了Editable接口的对象。在这个对象上,您可以调用insert()方法,在特定位置插入文本。
我通过阅读文档发现了这一点,但从未自己使用过。但是对于您的需求,在EditText中选定位置插入字符,以下内容应该有效:
Editable text = entry.getText();
text.insert(entry.getSelectionStart(), "h");

谢谢Jan-Henk。我没有理解它实现了可编辑接口,所以我没有检查那里。这是我正在使用的。这样我只需使用已选定的插入点即可。 Editable entryE1 = entry.getText(); entryE1.insert(entry.getSelectionStart(), "1"); 看起来效果很好。 - Bill Maney
我已经更新了我的答案,加入了你提到的getSelectionStart()方法。 - Jan-Henk

0
假设您有一个名为str的字符串,其中包含“blablahblah”,您想将其变为“blahblahblah”,可以执行以下操作:
String newString = str.substring(0, 3) + "h" + str.substring(3);

取前三个字符,加上新的字母,再放回原来的位置。因此,您可以从EditText中获取字符串,按照这种方式进行更改,然后将新字符串作为EditText的新值放回去。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接