The textView is used to shows some text inside the activity. However, the biggest drawback of textView is that the text inside can’t be formatted. If your are creating an app that needs to show a lot of formatted text then textView isn’t the best option for you.
However, wouldn’t it be nice if you could just embed HTML text inside the textView?
It would solve all our problems isn’t it.
You can actually show HTML inside a textView if you follow the steps in the article.
The end result would look something like this:
The procedure is as follows:
- Add a textView to your activity. Delete the default text generated by Android Studio, that is this line:
Finally your textView should look something like this:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/textView1" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" />
- Then go to the strings.xml file to create a string resource that will contain the HTML that you want to show inside the textView. However, there is one thing you need to remember. Make sure that you wrap your HTML within:
<![CDATA[ your_HTML_here ]]>
So that the string resource looks like this:
<string name="htmltext"> <![CDATA[ <h1>Heading</h1> <h3>Sub-heading</h3> <p></p> <br>Content/body</br> <br>More text</br> ]]> </string>
‘strings.xml’ can be found in app>res>values> strings.xml
- Then go to the JAVA file of your Activity and there in the OnCreate method copy the following lines of code:
TextView newtext = (TextView) findViewById(R.id.textView1); newtext.setText(Html.fromHtml(getString(R.string.htmltext)));
Make sure that the id of the textView matches the id that you assigned to your textView in step #1 and the name of the string resource matches the name of the string resource you created in step#2.
Well that’s all you need to do. Now if you run your app in the emulator then you can see that HTML displays correctly. Something like this:
Hope you found it useful.
Leave your doubts/questions in the comments section below.