Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop EditText scrolling when changing text (Android)

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);
        }
    }
}
like image 822
Person Avatar asked May 20 '26 14:05

Person


1 Answers

Alternatively, there is a method called setTextKeepState(CharSequence text). See TextView docs.

like image 114
willlma Avatar answered May 22 '26 08:05

willlma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!