Foreword
A Android application I wrote before. When the post is inserted into the expression, there is a bug, that is, it is impossible to insert the expression string at the cursor specified in the Edittext. The expression string added at each time is to the end of the text. After analyzing the APK source code, I found that it was not properly handled the emoji string adding method in the OnClick response event of the emoji. Here is how to insert the emoji string at the EditText specified optical indicator.
The method of inserting emoji string at Edittext cursor
Since the emoticon string is inserted in the Edittext control, the EditText control object is required first. The example source code is as follows:
EditText Redittext = (Edittext) FindViewByid (R.id.r_edittext);
Get the current EditText control object. The next step is to save the existing string in the current EditText. The example source code is as follows:
String oricontent = redittext.gettext (). Tostring ();
Next, it is to get the position of the cursor. Use the getSelectionStart () method provided by the EditText control. However, it should be noted here that when there is no cursor in Edittext, the method will return to -1. This is obviously not the position of the cursor we want, so it is best to compare with 0. The example source code is as follows:
int index = math.max (redittext.getselectionStart (), 0); 0);
The rest is to insert the emoji string at the given cursor position, and then set the new cursor position. The source code of complete insertion emoticons is as follows:
Private Void Insertemotion (String Insertemotion) {String Orgenttent = Redittext.gettext (). Tostring (); Start (), 0); StringBuilder Sbuilder = New StringBuilder (Oricontent); Sbuilder.Insert ( index, insertemotion); redittext.setText (sbuilder.tostring ()); reditText.Setselection (index + insertemotion.Length ());}