Android中实现部分字体颜色改变的方式

一、在string.xml文件中定义字符串资源,使用CDATA的方式,具体如下所示

<string name= "test_string1"><Data><![CDATA[<font color="#ff5a00">你好吗?</font>]]></Data>我很好呀!</string>

<string name= "test_string2"><Data><![CDATA[<font color="#ff5a00">你好吗?你好吗?你好吗?</font>]]></Data>\n\n\n我很好呀!</string>

二、在代码中使用Html解析,具体如下所示

//改变字体颜色
TextView textView1 = (TextView) findViewById(R.id.text1);        textView1.setText(Html.fromHtml(getResources().getString(R.string.test_string1)));

//改变字体颜色,并且实现换行,换行符"\n""<br/>"来替换
TextView textView2 = (TextView) findViewById(R.id.text2);
String testString = getResources().getString(R.string.test_string2);
testString = testString.replace("\n", "<br/>");
textView2.setText(Html.fromHtml(testString));

三、效果如下所示
这里写图片描述

四、详细代码
1.布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

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

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

</LinearLayout>

2.资源文件

<resources>
    <string name="app_name">My Application</string>
    <string name= "test_string1"><Data><![CDATA[<font color="#ff5a00">你好吗?</font>]]></Data>我很好呀!</string>
    <string name= "test_string2"><Data><![CDATA[<font color="#ff5a00">你好吗?你好吗?你好吗?</font>]]></Data>\n\n\n我很好呀!</string>
</resources>

3.代码文件

package com.my.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class ChangeColorActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_color_layout);

        //改变字体颜色
        TextView textView1 = (TextView) findViewById(R.id.text1);
        textView1.setText(Html.fromHtml(getResources().getString(R.string.test_string1)));

        //改变字体颜色,并且实现换行,换行符"\n""<br/>"来替换
        TextView textView2 = (TextView) findViewById(R.id.text2);
        String testString = getResources().getString(R.string.test_string2);
        testString = testString.replace("\n", "<br/>");
        textView2.setText(Html.fromHtml(testString));
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值