Package cc. testspannablestringbuilder; import android. OS. bundle; import android. text. spannable; import android. text. spannableStringBuilder; import android. text. style. foregroundColorSpan; import android. widget. textView; import android. app. activity; import android. graphics. color;/*** Demo Description: * use SpannableStringBuilder to set the Color of some text in TextView. ** Note: * mSpannableStringBuilder. setSpan * (new ForegroundColorSpan (Color. RED), 1, 3, Spannable. SPAN_EXCLUSIVE_INCLUSIVE); * First parameter: Color * second parameter: Start position * third parameter: end position * third parameter: SPAN_EXCLUSIVE_INCLUSIVE. it is used to further limit and describe the second and third parameters. * This field indicates that 1 is not included, but 3 is included. it can be understood literally */public class MainActivity extends Activity {private TextView mTextView; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {MTextView = (TextView) findViewById (R. id. textView); String str = "Hello everyone! "; SpannableStringBuilder mSpannableStringBuilder = new SpannableStringBuilder (str); mSpannableStringBuilder. setSpan (new ForegroundColorSpan (Color. RED), 1, 3, Spannable. SPAN_EXCLUSIVE_INCLUSIVE); mSpannableStringBuilder. setSpan (new ForegroundColorSpan (Color. GREEN), 5, 9, Spannable. SPAN_EXCLUSIVE_INCLUSIVE); mTextView. setText (mSpannableStringBuilder );}}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:layout_centerInParent="true" /></RelativeLayout>