5
Button btnBold = (Button) findViewById(R.id.btnBold);
    btnBold.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick (View v){
        startSelection = etx.getSelectionStart();
        endSelection = etx.getSelectionEnd();


        Spannable s = etx.getText();
        s.setSpan(new StyleSpan(Typeface.BOLD), startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
});


Button btnNormal = (Button) findViewById(R.id.btnNormal);
    btnNormal.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick (View v){
        startSelection = etx.getSelectionStart();
        endSelection = etx.getSelectionEnd();
        Spannable s = etx.getText();
        s.setSpan(new StyleSpan(Typeface.NORMAL), startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }
});

With above code I'm trying to BOLD and UNBOLD selected text from button.

For example : I have made this line bold by selecting all at once.

now, If I apply unbold by selecting some of the text in above line then it won't work.

I have already gone through these answers already but no luck:

How to unbold the selected text in Edittext Android?

Remove style on spans

Removing style from selected text in edittext

Problem with above solutions is that, for example, If you selected five words from text and made them bold and now you selected some part of that bold text and unbold then all five words will be unbold.

Solutions mentioned in above links uses following code to remove span, which is not solving problem correctly

Spannable str = this.getText();
StyleSpan[] spans = str.getSpans(sStart, sEnd, StyleSpan.class);
for (int i = 0; i < spans.length; i++) {
    if (spans[i].getStyle() == android.graphics.Typeface.BOLD){
        str.removeSpan(spans[i]);
    }
}

I'm not able to find Android API where I can remove span from selected range. Any help is appreciated, Thank You.

Sumitkumar Dhule
  • 409
  • 5
  • 10

0 Answers0