定义三个TextView
<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/welcome"
android:textSize="18sp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="18sp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="18sp" />
</LinearLayout>
第一个直接通过@string
引用,第二个通过getText
方法获取字符串,第三个通过getString
方法获取字符串。
<string name="welcome">Welcome to <font color="#7C4DFF">Android</font>!</string>

<string name="welcome">Welcome to <font color="#7C4DFF">Android</font>!</string>

getString
使用Html.fromHtml()
方法
mTextView3.setText(Html.fromHtml(getString(R.string.welcome)));

再次使用第一个字符串,并调用Html.fromHtml()
方法
mTextView2.setText(getText(R.string.welcome));
mTextView3.setText(Html.fromHtml(getString(R.string.welcome)));

在代码中使用getString
方法,想要保留Html样式,必须进行转义,并调用Html.fromHtml()
方法。但是在strings.xml
中如果包含的标签过多,使用转义符不方便阅读,并且写起来比较麻烦,可以使用CDATA
进行包裹。
<string name="welcome"><![CDATA[Welcome to <font color="#7C4DFF">Android</font>!]]</string>

网友评论