I'm working with with editText
and buttons
and layout contains four buttons
and one editText
etDescription
Now, here I'm styling my editText's selected text
by clicking on buttons
with using this code
CharacterStyle styleBold, styleItalic, styleUnderline, styleStrike;
styleBold = new StyleSpan(Typeface.BOLD);
styleItalic = new StyleSpan(Typeface.ITALIC);
styleUnderline = new UnderlineSpan();
styleStrike = new StrikethroughSpan();
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnItalic:
makeIt(styleItalic);
break;
case R.id.btnBold:
makeIt(styleBold);
break;
case R.id.btnUnderline:
makeIt(styleUnderline);
break;
case R.id.btnStrike:
makeIt(styleStrike);
break;
}
}
private void makeIt(CharacterStyle characterStyle) {
String wholeTextUnder = etDescription.getText().toString();
int startu = etDescription.getSelectionStart();
int endu = etDescription.getSelectionEnd();
SpannableStringBuilder sbu = new SpannableStringBuilder(wholeTextUnder);
sbu.setSpan(characterStyle, startu, endu, 0);
etDescription.setText(sbu);
}
It's giving my whole editText
a single style
Like when i select text 1-10 and then make it's bold it works!
but, when i select other text then make it some other like italic
, strike
, underline
then pervious text become normal and new changes successfully.
I want that perivous text will also stay same
Waiting for answer!
Thanks in advance!!
Happy coding!
Your problem is when you call String wholeTextUnder = etDescription.getText().toString();
You already change it to String
it means any Span
you set will be clear. Try this.
private void makeIt(CharacterStyle characterStyle) {
CharSequence wholeTextUnder = etDescription.getText();
int startu = etDescription.getSelectionStart();
int endu = etDescription.getSelectionEnd();
SpannableStringBuilder sbu = new SpannableStringBuilder(wholeTextUnder);
sbu.setSpan(characterStyle, startu, endu, 0);
etDescription.setText(sbu);
}