改变textview的部分字体和颜色

    textview是android系统体提供显示文本的一类组件,在实际的使用中,一段文字可能需要不同的颜色和文字。常用的实现方法有两类,分别是textview的textview.setText(Html.fromHtml("显示的内容和样式"))方法和SpannableString。SpannableString方法比较灵活。
实现如下:

1.布局文件定义4个textview

<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:orientation="vertical"
    >


    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text1" />


    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text2" />


    <TextView
        android:id="@+id/tv3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text3" />


    <TextView
        android:id="@+id/tv4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text4" />


</LinearLayout>

2.找到四个textview,并实现效果

private TextView tv1 = null;
private TextView tv2 = null;
private TextView tv3 = null;
private TextView tv4 = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
tv4 = (TextView) findViewById(R.id.tv4);
tv1.setText(Html.fromHtml("我是<font color='#ff0000'><big>第一个</big>textview </font>"));
tv2.setText(Html.fromHtml("<h1>我是第二个textview</h1>"));
tv3.setText("我是第三个textview");
Spannable sp=new SpannableString(tv3.getText());
sp.setSpan(new AbsoluteSizeSpan(50), 2, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sp.setSpan(new ForegroundColorSpan(Color.RED), 2, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv3.setText(sp);
tv4.setText(Html.fromHtml("<font color='#ffff00'> 
<small>我是第四个textview</small></font>"));`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值