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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With