How to underline text in android


Download how to underline text in android sample

Sometimes we want to add some html like styles in our text. There are 3 different approach to do it:

  • By using SpannableString
  • By using setPaintFlags() method of view
  • By using Html.fromHtml()
  • By using string resource xml

1. Using SpannableString


To make text underline, put below given line of code in onCreate method of your activity:

2. Using setPaintFlags()


We can use setPaintFlags method to make a text underline:

3. Using Html.fromHtml(htmlString)


We can use Html.fromHtml(htmlString) to add html like styles:

4. Using string resource xml

It can be achieved if we are using a string resource xml file, which supports HTML tags like <b></b>, <i></i> and <u></u>.

Example


In this example, I have tried to demonstrate all 4 approach to underline a text. Several html tags are supported if you want to use approach 3 and 4.

Here is the result screen of this example

Result of sample

How to make text underline?

Step 1: Create a new project in Android Studio and name it Underline text in android.

Step 2: Open res -> layout -> activity_main.xml and add following code

activity_main.xml

Step 3: Open your MainActivity.java and onCreate method set your desired font for view. Source of my MainActivity.java is given below:

MainActivity.java

Step 4: Open res -> values ->strings.xml and replace it with below given code.

MainActivity.java

Step 5: Clean and run the project to see the result.


Share & Like

Tutorial topics

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.