Objective
previously written on an Android application, in reply to the post insert expression when there is a bug, that is, can not be specified in the EditText at the cursor inserted in the expression string, each added expression string ran to the end of the text. Analysis of the APK source code, found in the expression Tray onclick response event did not correctly handle the expression string Add method, here to record how at the edittext specified cursor inserted expression string.
method of inserting an expression string at the EditText cursor
now that you're inserting an expression string into a EditText control, you first need to get the EditText control object, the sample source is as follows:
EditText Redittext = (edittext) Findviewbyid (R.id.r_edittext);
Gets the current EditText control object, the next step is to save the string already in the current edittext, sample source code is as follows:
String oricontent = Redittext.gettext (). toString ();
Next, 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 the EditText, this method will return-1, which is obviously not the position of the cursor we want, so it is best to compare to 0, the sample source is as follows:
int index = Math.max (Redittext.getselectionstart (), 0);
The rest is to insert the expression string at the given cursor position, and then set the new cursor position. The complete Insert Expression example 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 ());
}