如何在EditText字段中间插入字符?
我正在做一个计算器,它可以接受像"3*(10^2-8)“这样的字符串表达式。我使用EditText字段来使字符串使用XML,如下所示:
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"?
发布于 2012-01-09 07:20:56
EditText小部件的方法getText()返回一个实现可编辑接口的对象。在这个对象上,您可以调用insert()方法在某个位置插入文本。
我通过阅读文档发现了这一点,但我自己从来没有用过它。但根据您的需要,要在EditText中的选定位置插入字符,应执行以下操作:
Editable text = entry.getText();
text.insert(entry.getSelectionStart(), "h");发布于 2012-01-09 06:50:56
假设你有一个名为str的字符串,它包含"blablahblah“,你想让它成为"blahblahblah”,你可以这样做:
String newString = str.substring(0, 3) + "h" + str.substring(3);取前3个,添加新字母,放置其他所有内容。因此,您可以从EditText中获取字符串,将其更改为这样,然后将新字符串作为EditText的新值。
https://stackoverflow.com/questions/8781972
复制相似问题