Full tutorial is given below. Dear Viewer we are working hard to maintain this website. We doesn't want any think from you. Its just a humble request If you thinks that this posts helps you please share this post with your friends.
Text Color of a Substring - Android Studio - Java
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" android:padding="10dp" tools:context=".MainActivity"> <TextView android:padding="10dp" android:id="@+id/text_view" android:textSize="25sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_centerInParent="true" /> </RelativeLayout>
MainActivity.java
package com.usmtip.myapplication; import android.graphics.Color; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //TextView TextView mTextView = findViewById(R.id.text_view); //text to set in TextView String 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 substring SpannableString mSpannableString = new SpannableString(mText); //color styles to apply on substrings ForegroundColorSpan mRed = new ForegroundColorSpan(Color.RED); //red color ForegroundColorSpan mGreen = new ForegroundColorSpan(Color.GREEN); //green color ForegroundColorSpan mBlue = new ForegroundColorSpan(Color.BLUE); //blue color //applying color styles to substrings mSpannableString.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 TextView mTextView.setText(mSpannableString); } }
0 Comments: