Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting long paragraphs in android TextView

I have a lot of text (more than 10000 words) which I would like to display on my android app. The text contains bullets, paragraphs and line breaks. I want to know how can I display on my app without manual editing. It is not possible to convert every line break to \n and every tab to \t. I have also tried parsing data in HTML and then using Html.fromHtml(getString(R.string.text)). However, the display that I get looks completely unformatted.

This is how I want the text to look like in the app:

like image 505
Khushboo Gandhi Avatar asked Oct 23 '25 01:10

Khushboo Gandhi


1 Answers

HTML tags are easy solutions for simple problems, like making a text bold, italic, or even displaying bullet points. To style text containing HTML tags, call Html.fromHtml method. Under the hood, the HTML format is converted into spans. Please note that the Html class does not support all HTML tags and CSS styles like making the bullet points another color.

val text = "My text <ul><li>bullet one</li><li>bullet two</li></ul>"
txtview.text = Html.fromHtml(text)

Spans allow you to implement multi-style text with finer-grained customization. For example, you can define paragraphs of your text to have a bullet point by applying a BulletSpan. You can customize the gap between the text margin and the bullet and the color of the bullet. Starting with Android P, you can even set the radius of the bullet point. You can also create a custom implementation for the span. Check out the "Create custom spans" section below to find out how.

val spannable = SpannableString("My text \nbullet one\nbullet two")
spannable.setSpan(
   BulletPointSpan(gapWidthPx, accentColor),/* start index */ 9, /* end index */ 18,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
   spannable.setSpan(BulletPointSpan(gapWidthPx, accentColor),/* start index */ 20, /* end index */ spannable.length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
 txtview.text = spannable

enter image description here

like image 83
Sanjay Bhalani Avatar answered Oct 24 '25 16:10

Sanjay Bhalani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!