美文网首页
Android字符串资源

Android字符串资源

作者: Carve_Time | 来源:发表于2018-03-15 13:24 被阅读49次

定义三个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>
image
    <string name="welcome">Welcome to &lt;font color="#7C4DFF">Android&lt;/font>!</string>

image

getString使用Html.fromHtml()方法

        mTextView3.setText(Html.fromHtml(getString(R.string.welcome)));
image

再次使用第一个字符串,并调用Html.fromHtml()方法

       mTextView2.setText(getText(R.string.welcome));
        mTextView3.setText(Html.fromHtml(getString(R.string.welcome)));
image

在代码中使用getString方法,想要保留Html样式,必须进行转义,并调用Html.fromHtml()方法。但是在strings.xml中如果包含的标签过多,使用转义符不方便阅读,并且写起来比较麻烦,可以使用CDATA进行包裹。

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

image

参考

相关文章

网友评论

      本文标题:Android字符串资源

      本文链接:https://www.haomeiwen.com/subject/pbicqftx.html