一、在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));
}
}