富文本的使用之二 设置TextView不同字段的颜色和背景颜色

来源:互联网 发布:数学英文词典软件 编辑:程序博客网 时间:2024/04/30 05:50

直接上代码

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView textView1 = (TextView) findViewById(R.id.textView1);        TextView textView2 = (TextView) findViewById(R.id.textView2);        TextView textView3 = (TextView) findViewById(R.id.textView3);        TextView textView4 = (TextView) findViewById(R.id.textView4);//两次加大字体,设置字体为红色(big会加大字号,font可以定义颜色)        textView1.setText(Html.fromHtml("北京市发布霾黄色预警,<font color='#ff0000'><big><big>外出携带好</big></big></font>口罩"));//设置字体大小为3级标题,设置字体为红色        textView2.setText(Html.fromHtml("北京市发布霾黄色预警,<h3><font color='#ff0000'>外出携带好</font></h3>口罩"));//设置字体大小为58(单位为物理像素),设置字体为红色,字体背景为黄色        textView3.setText("北京市发布霾黄色预警,外出携带好口罩");        Spannable span = new SpannableString(textView3.getText());        span.setSpan(new AbsoluteSizeSpan(58), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        span.setSpan(new ForegroundColorSpan(Color.RED), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        span.setSpan(new BackgroundColorSpan(Color.YELLOW), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        textView3.setText(span);//两次缩小字体,设置字体为红色(small可以减小字号)        textView4.setText(Html.fromHtml("北京市发布霾黄色预警,<font color='#ff0000'><small><small>外出携带好</small></small></font>口罩"));    }}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/textView1" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/textView2" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/textView3" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/textView4" /></LinearLayout>
阅读全文
0 0
原创粉丝点击