Search code examples
javaandroidandroid-edittext

How to add a Character to an EditText where the User's Cursor is


I want the user to be able to press a button and add a certain character such as "<", and after the character is added in the position the cursor is, I want the cursor to move to after the added character, like he presses it on his keyboard.

If I just save the current content of the EditText and add a character it will just add it to the end, and will reset the position of the cursor.


Solution

  • You can try doing something as follows:

    EditText edittext = findViewById(R.id.edittext);
    Button button = findViewById(R.id.button)b
    
    button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    int cursorPosition = edittext.getSelectionStart();
                    String enteredText = edittext.getText().toString();
                    String startToCursor = enteredText.subSequence(0, cursorPosition);
                    String cursorToEnd = enteredText.subSequence(cursorPosition, enteredText.length());
    
                    String finalString = startToCursor + "<" + cursorToEnd;
                    edittext.setText(finalString);
                    edittext.setSelection(cursorPosition+1);
                )
    });
    

    References: https://stackoverflow.com/a/6900610/10487248 , https://stackoverflow.com/a/20838294/10487248