【发布时间】:2012-02-13 02:36:18
【问题描述】:
我想清除光标位置之前的 EditText 上的整个文本。假设我的文本是 1234567890,光标在字符 4 之后像这样 1234|567890 现在我的要求是我有一个自定义按钮,删除光标位置之前的文本。
我正在使用editext.getText().clear(); 来清除文本,但它会清除整个文本。如果光标在文本的末尾,那很好。
是否有可能达到我的要求?如果是怎么办?请帮我解决这个问题。
【问题讨论】:
我想清除光标位置之前的 EditText 上的整个文本。假设我的文本是 1234567890,光标在字符 4 之后像这样 1234|567890 现在我的要求是我有一个自定义按钮,删除光标位置之前的文本。
我正在使用editext.getText().clear(); 来清除文本,但它会清除整个文本。如果光标在文本的末尾,那很好。
是否有可能达到我的要求?如果是怎么办?请帮我解决这个问题。
【问题讨论】:
以下是处理方法:
您将使用以下方法获得光标位置:
editText.getSelectionStart();
或
editText.getSelectionEnd();
注意:如果没有选择文本,两种方法都将返回相同的索引。
然后将文本 EditText 和
然后再次设置为EditText。像这样:
int pos = editText.getSelectionStart();
String myText = editText.getText().toString();
//sub-string it.
String subStringed = myText.substring(pos, myText.length());
//set it again..
editText.setText(subStringed);
【讨论】:
以下答案可能会对您有所帮助。它非常适合我
在EditText光标的选定位置插入文本/字符
int start = edtPhoneNo.getSelectionStart(); //this is to get the cursor position
String s="sagar";//s="0123456789";
edtPhoneNo.getText().insert(start, s);
//this is to set the cursor position by +1 after inserting char/text
edtPhoneNo.setSelection(start + 1);
删除EditText光标选定位置的文本/字符
int curPostion = edtPhoneNo.getSelectionEnd();
SpannableStringBuilder selectedStr = new
SpannableStringBuilder(edtPhoneNo.getText());
selectedStr.replace(curPostion - 1, curPostion, "");
edtPhoneNo.setText(selectedStr);
//this is to set the cursor position by -1 after deleting char/text
edtPhoneNo.setSelection(curPostion - 1);
将EditText光标设置在最后一个位置
edtPhoneNo.setSelection(edtPhoneNo.getText().length());
这是EditText 的 XML 代码
<EditText
android:id="@+id/edtPhoneNumber"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:focusable="true"
android:focusableInTouchMode="true"
android:maxLines="1" />
【讨论】: