Get Spannable String from EditText

I set SpannableString to EditText, now I want to get this text from EditText and get its markup information. I tried like this

SpannableStringBuilder spanStr = (SpannableStringBuilder) et.getText().; int boldIndex = spanStr.getSpanStart(new StyleSpan(Typeface.BOLD)); int italicIndex = spanStr.getSpanStart(new StyleSpan(Typeface.ITALIC)); 

but it gives an index of -1 for both bold and italics, although it shows the text in italics and bold.

Please, help.

+8
android spannablestring
source share
1 answer

From the code you posted, you pass the new gaps to spanStr and ask him to find them. You will need a link to instances of the areas that are actually applied. If this is not possible or you do not want to track gaps directly, you can simply call getSpans to get all the spans. Then you can filter this array for whatever you want.

If you don't care about passages in particular, you can also just call Html.toHtml (spanStr) to get the version tagged with HTML.

edit : add sample code

This will capture all the StyleSpans application styles you want.

  /* From the Android docs on StyleSpan: "Describes a style in a span. * Note that styles are cumulative -- both bold and italic are set in * separate spans, or if the base is bold and a span calls for italic, * you get bold italic. You can't turn off a style from the base style."*/ StyleSpan[] mSpans = et.getText().getSpans(0, et.length(), StyleSpan.class); 

Here is a link to StyleSpan documents.

To select the gaps you want, if you have different gaps mixed with the collection / array, you can use instanceof to find out what sizes you have. This snippet checks to see if a particular mSpan instance of StyleSpan, and then prints its indexes and start and end flags. Flags are constants describing the behavior of range outlines, for example: whether they include and apply styling to text at the beginning and end indices or only for entering text with an index inside the start / end range).

  if (mSpan instanceof StyleSpan) { int start = et.getSpanStart(mSpan); int end = et.getSpanEnd(mSpan); int flag = et.getSpanFlags(mSpan); Log.i("SpannableString Spans", "Found StyleSpan at:\n" + "Start: " + start + "\n End: " + end + "\n Flag(s): " + flag); } 
+10
source share

All Articles