An Android app that was written before the preface has a bug when replying to a post inserting an emoticon, that is, the expression string cannot be inserted at the cursor specified in EditText, each time the expression string is added to the end of the text. Analysis of the APK source code, found to be in the onclick response event of the expression disk does not correctly handle the addition of the expression string, here to record how to insert the expression string at the EditText specified cursor.
EditText the method of inserting an expression string at the cursor since it is inserting an expression 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 position of the cursor. Use the Getselectionstart () method provided by the EditText control. However, it should be noted that when there is no cursor in EditText, using this method will return-1, which is obviously not the cursor position we want, so it is best to compare with 0, the sample source code is as follows:
int index = Math.max (Redittext.getselectionstart (), 0);
All that remains is to insert the expression string at the given cursor position, and then set the new cursor position. The complete example of inserting emoticons 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 ());}
Android edittext Insert Emoticons (string) to cursor position