0

I want to change the Text style on a button click. When the user clicks the button it makes the selected area italic. When the user clicks it again I want the selected area to become non italic. How is this possible. This is my code:

        if (id == R.id.italic) {

        int startSelection = noteContent.getSelectionStart();
        int endSelection = noteContent.getSelectionEnd();
        Spannable spannable = noteContent.getText();

        StyleSpan[] spans = spannable.getSpans(startSelection, endSelection, StyleSpan.class);

        if (spans.length == 0 ) {

            spannable.setSpan(new StyleSpan(Typeface.ITALIC), startSelection, endSelection , 0);

        } else {

            StyleSpanRemover spanRemover = new StyleSpanRemover();

            spanRemover.RemoveStyle(spannable, startSelection, endSelection, Typeface.ITALIC);
        }
    }

When I run this code the selected area becomes Italic on the button click. Then if I were to click the button again the same selected area would become un italic. Sounds like it works fine. But it does not. For some reason if I were to take the same selected area and re italicize it it will not become italic. This is because spans.length is still set to 1. It did not go back to zero when I made the Italicized text normal. Any idea on how to set spans.length back to 0?

Jordan
  • 407
  • 5
  • 20
  • You set that spannable back to the edit text using `noteContent.setSpan(spannable);`. That is assuming you have setup the spans right, just glanced at those but setting the span to the view is a start :P – zgc7009 Sep 14 '15 at 23:00
  • noteContent is the edit text you get set span with that variable – Jordan Sep 15 '15 at 02:20
  • Sorry setText(spannable); not setSpan(spannable); – zgc7009 Sep 15 '15 at 02:59

0 Answers0