Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

android - Insert character between the cursor position in edit text

My code is :

EditText edt
    
edt.addTextChangedListener(new TextWatcher() {
    
    @Override
    public void afterTextChanged(Editable arg0) {
    
        final String number = edt.getText().toString();
    
        int count = arg0.length();
        edt.setSelection(count);
    }
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        final String number = edt.getText().toString();
    }
}

I have a dialpad too. When I click a particular number in the dial pad, I need to add that number to the current cursor position. Also, when I press delete, I need to delete the number from the current cursor position.

Dialpad Image

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the following code

int start =editText.getSelectionStart(); //this is to get the the cursor position
String s = "Some string";
editText.getText().insert(start, s); //this will get the text and insert the String s into   the current position

Here is the code to delete selected text from EditText

int start = t1.getSelectionStart();  //getting cursor starting position
int end = t1.getSelectionEnd();      //getting cursor ending position
String selectedStr = t1.getText().toString().substring(start, end);    //getting the selected Text
t1.setText(t1.getText().toString().replace(selectedStr, ""));    //replacing the selected text with empty String and setting it to EditText

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...