I'm trying to program a syntax highlighter for Android. The highlighting algorithm which runs in a separate AsyncTask
thread itself works great, and returns a SpannableString
with all the necessary formatting.
However, whenever I do editText.setText(mySpannableString, BufferType.SPANNABLE)
to display the highlighted text the EditText
scrolls back to the beginning and selects the beginning of the text.
Obviously, this means that the user cannot keep typing whilst the text is being processed by the syntax highlighter. How can I stop this? Is there any way I can update the text without the EditText
scrolling? Here is an outline of the code:
public class SyntaxHighlighter extends Activity {
private EditText textSource;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
textSource = (EditText) findViewById(R.id.codeSource);
// Syntax Highlighter loaded text
new XMLHighlighter().execute(textSource.getText().toString());
}
// Runs on Asyncronous Task
private class XMLHighlighter extends AsyncTask<String, Void, SpannableString> {
protected SpannableString doInBackground(String... params) {
return XMLProcessor.HighlightXML(params[0]);
}
protected void onPostExecute(SpannableString HighlightedString) {
textSource.setText(HighlightedString, BufferType.SPANNABLE);
}
}
}
I suggest the following:
protected void onPostExecute(SpannableString HighlightedString) {
int i = textSource.getSelectionStart();
textSource.setText(HighlightedString, BufferType.SPANNABLE);
textSource.setSelection(i);
}
to place the cursor back to its position after you changed the content.