user3900924
user3900924

Reputation: 93

android SPAN_EXCLUSIVE_EXCLUSIVE not working properly

I am trying to set span on a SpannableStringBuilder using flag SPAN_EXCLUSIVE_EXCLUSIVE and I am facing problem on further editing the text to which I am setting span.

Expected behaviour 1: Original text. 2: Text added before. 3: Text added after with space.

Unexpected Behaviour on adding text after styled text

I don't want the added text to be styled, and want to know what am I doing wrong.

EDIT 1: The issue is happening on Moto X Play, but is not reproduced on Nexus 5X. Still testing on other devices.

Upvotes: 8

Views: 1147

Answers (2)

Achraf Amil
Achraf Amil

Reputation: 1375

TL;DR: Using some IMEs, like Gboard, when adding a char directly after a word (without space) the IME will replace the whole word tric with trick instead of just appending the c.

Detailed asnwer: How IMEs work with editors.

How some IMEs dictate commands to editors IMEs communicate with editors (e.g. EditText) through InputConnection interface where they can send commands following user input, and get current text.

Gboard IME works in the following way:

  • gets text before and after cursor
  • detects the currently "composing" word and asks the editor to highlight and remember it (usually results in the word being underlined - check screenshot below)

Being aware of the currently composing word enables many features like suggesting words or auto-correcting spelling.

  • Whenever a char is inputted by the user, Gboard will ask the editor to set the currently composing text to a new value, i.e. replace trick by tricky
  • After a space is inputted, Gboard will do a final replace of currently composing region, eventually auto-correcting spelling
  • Currently composing region is reset to the next word.

This unfortunately breaks what we would normally expect from SPAN_EXCLUSIVE_EXCLUSIVE.

screenshot with Gboard underlining the currently composing region

Upvotes: 0

Miroslav Javorský
Miroslav Javorský

Reputation: 187

You just probably add text not the way you should. Use .insert() and .append() methods of SpannableStringBuilder to add additional text.

I just tried what you try to achieve and here is the result:

TextView hratkyTextView = (TextView) findViewById(R.id.spannableHratkyTextView);

final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold

// "Test text" part (in bold)
SpannableStringBuilder builder = new SpannableStringBuilder("Test text");
builder.setSpan(bss, 0, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Prepending "before" (non-bold)
builder.insert(0, "before");

// Appending " after_with_space" to the end of the string
builder.append(" after_with_space");

hratkyTextView.setText(builder);

Result: Nexus 7 Emulator running MainActivity with this code

Upvotes: 0

Related Questions