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="com.codinginflow.spannablestringexample.MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I want THIS and THIS to be colored" android:textSize="20sp" 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.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.BackgroundColorSpan; import android.text.style.ForegroundColorSpan; 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 = "I want THIS and THIS to be colored"; SpannableString ss = new SpannableString(text); SpannableStringBuilder ssb = new SpannableStringBuilder(text); ForegroundColorSpan fcsRed = new ForegroundColorSpan(Color.RED); ForegroundColorSpan fcsGreen = new ForegroundColorSpan(Color.GREEN); BackgroundColorSpan bcsYellow = new BackgroundColorSpan(Color.YELLOW); ssb.setSpan(fcsRed, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(fcsGreen, 16, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(bcsYellow, 27, 34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.append(" and this to be appended"); textView.setText(ssb); } }