Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text in multiple EditText controls simultaneously

I've got the following problem: I'm trying to highlight text in multiple EditText controls simultaneously by calling viewXYZ.setSelection(int, int), but the selection is only visible on the focused view.

Is there any way to bypass this, to highlight text in an unfocused EditText? Maybe by overloading the onDraw() methods?

like image 823
Wolfram Hofmeister Avatar asked May 26 '12 18:05

Wolfram Hofmeister


Video Answer


1 Answers

I know, but its (as far as I know?) the only way to mark text in an EditText control.

EditText supports Spannable objects, so you can apply highlights to text (e.g., background colors) yourself.

This sample project demonstrates a search field that applies a background color to a larger piece of text based upon the search results. The key part is the searchFor() method:

  private void searchFor(String text) {
    TextView prose=(TextView)findViewById(R.id.prose);
    Spannable raw=new SpannableString(prose.getText());
    BackgroundColorSpan[] spans=raw.getSpans(0,
                                             raw.length(),
                                             BackgroundColorSpan.class);

    for (BackgroundColorSpan span : spans) {
      raw.removeSpan(span);
    }

    int index=TextUtils.indexOf(raw, text);

    while (index >= 0) {
      raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
          + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      index=TextUtils.indexOf(raw, text, index + text.length());
    }

    prose.setText(raw);
  }

Note, though, that your "output string" probably should be a TextView, not an EditText. EditText is for input, not output.

like image 125
CommonsWare Avatar answered Oct 31 '22 19:10

CommonsWare