xml文件:

<LinearLayout 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"
    android:gravity="center_horizontal"
    android:orientation="vertical">
<TextView
    android:id="@+id/tv_show"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

入口:

tv_show=findViewById(R.id.tv_show);
//将需要显示的汉字保存在SpannableString对象中
SpannableString spannableString = new SpannableString("一切皆有可能");
//设置要显示的颜色
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0000"));
/**
 *
 Spanned.SPAN_INCLUSIVE_EXCLUSIVE  从起始下标到终了下标,包括起始下标

 Spanned.SPAN_INCLUSIVE_INCLUSIVE  从起始下标到终了下标,同时包括起始下标和终了下标

 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE  从起始下标到终了下标,但都不包括起始下标和终了下标

 Spanned.SPAN_EXCLUSIVE_INCLUSIVE  从起始下标到终了下标,包括终了下标
 */
//spannableString.setSpan("显示的颜色","起始下标","终止下标", "指定包不包括下标");
spannableString.setSpan(colorSpan,4,spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//显示
tv_show.setText(spannableString);

显示界面:

在TextView控件中指定汉字指定颜色显示


主要是功能,忽视界面,为了自己以后可以复习,请多多保函。

相关文章: