Latest News

Text Style Of A Substring - Android Studio - Kotlin

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 1: Create a new Project or open new project

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/text_view"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.kt

package com.blogspot.atifsoftwares.textstleskotlinimport android.graphics.Typefaceimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.text.SpannableStringimport android.text.Spannedimport android.text.style.StrikethroughSpanimport android.text.style.StyleSpanimport android.text.style.UnderlineSpanimport kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//the text to set in TextViewval 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 substringsval mBSpannableString = SpannableString(mText)//styles to apply on substringsval mBold = StyleSpan(Typeface.BOLD) //boldval mItalic = StyleSpan(Typeface.ITALIC) //italicval mBoldItalic = StyleSpan(Typeface.BOLD_ITALIC) //bold italicval mStrikeThrough = StrikethroughSpan() //strike throughval mUnderlineSpan = UnderlineSpan() //underline//applying styles to substringsmBSpannableString.setSpan(mBold , 16 , 20 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)mBSpannableString.setSpan(mItalic , 25 , 31 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)mBSpannableString.setSpan(mBoldItalic , 36 , 47 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)mBSpannableString.setSpan(mStrikeThrough , 52 , 66 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)mBSpannableString.setSpan(mUnderlineSpan , 71 , 80 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)//setting text to TextViewtext_view.text = mBSpannableString}}

Step 3: Run Project

Output


Check this tutorial for java

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