Set HTML formatted text inside TextView in android

Display html embedded code in android app using Spanned.

Html is one of the best static online development language to create smart, simple and beautiful websites. Now android gives us the facility to embedded html code into android app and design your own apps using html. So here is the step by step tutorial to Set HTML formatted text inside TextView in android.

android-project-download-code-button

How to Set HTML formatted text inside TextView in android.

Code for MainActivity.java file.

 package com.android_examples.com.textviewhtmldisplay;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

 Button DisplayHTMLButton;
 TextView HoldHTML;
 
 Spanned ConvertHTML;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 DisplayHTMLButton = (Button)findViewById(R.id.button1);
 HoldHTML = (TextView)findViewById(R.id.textView1);
 
 //Define your html code here. 
 
 ConvertHTML = Html.fromHtml("<H2>H2 TAG APPLY HERE</H2></BR> " +
 "<strong>Bold HTML TAG APPLY HERE</strong>" );
 
 DisplayHTMLButton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 //Setting up html code into TextView.
 
 HoldHTML.setText(ConvertHTML);
 
 }
 });
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.textviewhtmldisplay.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="TextView Text Display Here"
 android:textAppearance="?android:attr/textAppearanceLarge" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="62dp"
 android:text="SHOW HTML FORMATTED TEXT INSIDE TEXTVIEW" />

</RelativeLayout>

Screenshots:

html embedded

Set HTML formatted text inside TextView in android

Click Here to download Set HTML formatted text inside TextView in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *