先看效果,
下面是代码,有注释的,大家很容易看懂的
MainActivity中TextView text1 = (TextView) findViewById(R.id.text1);
SpannableStringBuilder builder = new SpannableStringBuilder(text1.getText().toString());
//ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色
//设置前景色
ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
ForegroundColorSpan yelloSpan = new ForegroundColorSpan(Color.YELLOW);
ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);
ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);
//第一个参数 设置用什么笔 第二个第三个参数,设置开始结束位置 开始结束的模式,有四种
/**
* Spannable.SPAN_EXCLUSIVE_EXCLUSIVE:前后都不包括,即在指定范围的前面和后面插入新字符都不会应用新样式
* Spannable.SPAN_EXCLUSIVE_INCLUSIVE :前面不包括,后面包括。即仅在范围字符的后面插入新字符时会应用新样式
* Spannable.SPAN_INCLUSIVE_EXCLUSIVE :前面包括,后面不包括。
* Spannable.SPAN_INCLUSIVE_INCLUSIVE :前后都包括。
*/
builder.setSpan(redSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(yelloSpan, 9, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(greenSpan, 16, 25, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(blueSpan, 26, 33, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置背景色 参数一样的
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.parseColor("#88888888"));
builder.setSpan(backgroundColorSpan, 0, 34, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text1.setText(builder);
布局文件中
android:textSize="25sp"
android:id="@+id/text1"
android:layout_width="wrap_content"
android:text="如果我們不曾相遇,你又會在哪裡,如果我們從不曾相識,人間又如何運行。"
android:layout_height="wrap_content"/>
就可以啦