Latest News

Text Style Of A Substring - Android Studio - Java

We will change the style of some sub-strings of text of TextView using the ''SpannableString'' class
✓BOLD
✓ITALIC
✓BOLD_ITALIC 
✓STRIKE-THROUGH 
✓UNDERLINE

VIDEO


Step 2: Code

activity_main.xml
<?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"><TextViewandroid:id="@+id/textView"android:textSize="18sp"android:textColor="#000"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>

MainActivity.java

package com.blogspot.atifsoftwares.textstyles;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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//TextViewTextView mTextView = findViewById(R.id.textView);//The text to set in TextViewString mText = "Our text can be BOLD and ITALIC and BOLD-ITALIC and STRIKE-THROUGH and UNDERLINE.";//Creating spannable string from normal string , we will use it to apply StyleSpan to substringsSpannableString mSpannableString = new SpannableString(mText);//styles to apply on substringsStyleSpan mBold = new StyleSpan(Typeface.BOLD); //bold styleStyleSpan mItalic = new StyleSpan(Typeface.ITALIC); //italic styleStyleSpan mBoldItalic = new StyleSpan(Typeface.BOLD_ITALIC); //bold italic styleStrikethroughSpan mStrikeThrough = new StrikethroughSpan(); //strike through styleUnderlineSpan mUnderlineSpan = new UnderlineSpan(); //underline style//applying styles to substringsmSpannableString.setSpan(mBold , 16 , 20 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mItalic , 25 , 31 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mBoldItalic , 36 , 47 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mStrikeThrough , 52 , 66 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mUnderlineSpan , 71 , 80 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//setting text to text viewmTextView.setText(mSpannableString);}}

Step 3: Run Project

Output


0 Response to "Text Style Of A Substring - Android Studio - Java"