Clearing the entire text before cursor position on

2019-07-21 17:15发布

问题:

I want to clear the entire text on EditText which is before the cursor position. Suppose i the text is 1234567890, the cursor is after the character 4 like this 1234|567890 Now my requirement is I have a custom button, which deletes the text before cursor position.

I am using editext.getText().clear(); to clear the text, but its clearing entire text. If the cursor is at end of text, it is good.

Is it possible to achieve my requirement ? If yes how ? Please help me regarding this.

回答1:

Here is how to deal with it:

You will get Cursor Position using:

editText.getSelectionStart();

or

editText.getSelectionEnd();

Note: if no text is selected, both methods will return the same index.

Then sub-string the text EditText and then set again to EditText. something like this:

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);


回答2:

Following answer may help you .Its working perfect for me

To insert the text/char at selected position of EditText cursor

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);

To delete the text/char at selected position of EditText cursor

 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);

To set EditText cursor at last position

 edtPhoneNo.setSelection(edtPhoneNo.getText().length());

This is XML code for EditText

<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" />