Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character between the cursor position in edit text

Tags:

android

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

like image 499
jennifer Avatar asked Oct 05 '11 12:10

jennifer


2 Answers

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
like image 197
Aju Avatar answered Nov 03 '22 21:11

Aju


To insert:

    String dialled_nos = dialpad_text.getText().toString();
    String number = view.getTag().toString(); // 1,2....9,0
    int start = dialpad_text.getSelectionStart(); 
    dialled_nos = new StringBuilder(dialled_nos).insert(start, number).toString();
    dialpad_text.setText(dialled_nos);
    dialpad_text.setSelection(start+1); // cursor will move to new position

To remove:

    String dialled_nos = dialpad_text.getText().toString();
    int remove_index_position = dialpad_text.getSelectionStart()-1; 
    StringBuilder dialled_nos_builder = new StringBuilder(dialled_nos);
    if(remove_index_position>=0) {
        dialled_nos_builder.deleteCharAt(remove_index_position);
        dialpad_text.setText(dialled_nos_builder.toString()); 
        dialpad_text.setSelection(remove_index_position);
    }
like image 30
user2458192 Avatar answered Nov 03 '22 19:11

user2458192