Insert the expression into the cursor position in android code

  • 2020-04-01 04:04:27
  • OfStack

preface
      An Android app I wrote earlier had a BUG inserting emojis in a reply post. It couldn't insert emojis at the cursor specified in the EditText, and every time the emojis were added, they went to the end of the text. After analyzing the apk source code, it was found that there was no proper adding method to the emoji string in the onClick response event of the emoji disk. Here, I recorded how to insert the emoji string at the specified cursor of the EditText.

Method to insert an expression string at the EditText cursor
      Now that you are inserting the emoji string in the EditText control, you first need to get the EditText control object, the sample source code is as follows:


  EditText rEditText = (EditText) findViewById(R.id.r_edittext); 

      Gets the current EditText control object, the next step is to save the existing string in the current EditText, the sample source code is as follows:


  String oriContent = rEditText.getText().toString(); 

      The next step is to get the cursor position. Use the getSelectionStart() method provided by the EditText control. However, it is important to note that when there is no cursor in the EditText, using this method will return -1, which is obviously not the desired cursor position, so it is best to compare it with 0 again. The sample source code is as follows:


  int index = Math.max(rEditText.getSelectionStart(), 0); 

      All that's left is to insert the emoji string at the given cursor position, and then set the new cursor position. The complete insert emoji sample source code is as follows:


  private void insertEmotion(String insertEmotion) { 
    String oriContent = rEditText.getText().toString(); 
    int index = Math.max(rEditText.getSelectionStart(), 0); 
    StringBuilder sBuilder = new StringBuilder(oriContent); 
    sBuilder.insert(index, insertEmotion); 
    rEditText.setText(sBuilder.toString()); 
    rEditText.setSelection(index + insertEmotion.length()); 
  } 


Related articles: