I am trying to change my string to make a badge with a number in the middle by using Spannable String. I can highlight the appropriate letter/number by setting the BackGrou
Hopefully this answer simplifies it for those still looking...
You can simply use a "chip" drawable. It does all the calculations correctly and is of much more minimal code.
See Standalone ChipDrawable
For completeness copied here:
res/xml/standalone_chip.xml
:
in java:
// Inflate from resources.
ChipDrawable chip = ChipDrawable.createFromResource(getContext(), R.xml.standalone_chip);
// Use it as a Drawable however you want.
chip.setBounds(0, 0, chip.getIntrinsicWidth(), chip.getIntrinsicHeight());
ImageSpan span = new ImageSpan(chip);
Editable text = editText.getText();
text.setSpan(span, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
End result: