Saturday, July 25, 2020

android kotlin - TextView html formatted text

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.text.Spanned
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // string inside html markup objects
        val htmlString : String  = "TextView first line... <br />" +
        "<b>Bold Text</b> | <i>Italic Text</i> and <br/>" +
                "<u>Underlined text</u>"

        // spanned is the interface for text that has
        // markup objects attached to ranges of it
        val spanned : Spanned = HtmlCompat
            // HtmlCompat is the backwards compatible version of Html
            .fromHtml(
                htmlString, // source
                // flag that separate block-level elements with blank lines
                // (two newline characters) in between
                HtmlCompat.FROM_HTML_MODE_LEGACY // flags
            )

        // finally, show html formatted text in text view
        textView.text = spanned
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="25dp"
        tools:text="TextView"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>