activity_main.xmlMainActivity.java
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="BOLD and ITALIC and BOLD-ITALIC and UNDERLINE and STRIKE-THROUGH" android:textAlignment="center" android:textSize="18sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
package com.codinginflow.spannablestringexample; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.StrikethroughSpan; import android.text.style.StyleSpan; import android.text.style.UnderlineSpan; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.text_view); String text = "BOLD and ITALIC and BOLD-ITALIC and UNDERLINE and STRIKE-THROUGH"; SpannableString ss = new SpannableString(text); StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); StyleSpan italicSpan = new StyleSpan(Typeface.ITALIC); StyleSpan boldItalicSpan = new StyleSpan(Typeface.BOLD_ITALIC); UnderlineSpan underlineSpan = new UnderlineSpan(); StrikethroughSpan strikethroughSpan = new StrikethroughSpan(); ss.setSpan(boldSpan, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(italicSpan, 9, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(boldItalicSpan, 20, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(underlineSpan, 36, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ss.setSpan(strikethroughSpan, 50, 64, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ss); } }