Latest News

Text Color Of A Substring - Android Studio - Java

We will change the color of some sub-strings of text of TextView using the ''SpannableString'' , and "ForeGroundColorSpan" classes using Android Studio IDE and Java language
✓RED 
✓GREEN 
✓BLUE

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="25sp"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.textcolor_java;import android.graphics.Color;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.SpannableString;import android.text.Spanned;import android.text.style.ForegroundColorSpan;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.text_view);//text to set in TextViewString mText = "Let's color some substrings: RED color , GREEN color , and BLUE color";//creating spannable string from normal string , we will use it to apply forgroundcolorspan to substringSpannableString mSpannableString = new SpannableString(mText);//color styles to apply on substringsForegroundColorSpan mRed = new ForegroundColorSpan(Color.RED); //red colorForegroundColorSpan mGreen = new ForegroundColorSpan(Color.GREEN); //green colorForegroundColorSpan mBlue = new ForegroundColorSpan(Color.BLUE); //blue color//applying color styles to substringsmSpannableString.setSpan(mRed , 29 , 32 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mGreen , 38 , 46 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);mSpannableString.setSpan(mBlue , 56 , 61 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//setting text to TextViewmTextView.setText(mSpannableString);}}

Step 3: Run Project

Output
Text Color of a Substring - Android Studio - Java

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