在Android中使用html
string.xml文件:
<?xmlversion="1.0"encoding="utf-8"?>
<resourcesxmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<stringname="hello">HelloWorld,TestHtmlActivity!</string>
<stringname="app_name">"TestHtml"</string>
<stringname="test_html"><Data><![CDATA[<b><fontcolor="#ffcce2">"Str类型:"<xliff:gid="format">%1$s</xliff:g>
"\nInt类型:"<xliff:gid="format">%2$d</xliff:g></font></b>]]></Data></string></resources>
注:<xliff:gid="format">%2$d</xliff:g>中的%2$d的字符含义如下:
%2:表示在源码中的第一个参数,$d表示该参数为整形,如果是$60d,则表示该整形必须为6位,如果传进的参数不足六位,如传递的是100,则会以0补足六位,得到的结果将是000100。
可以这样定义string,如:<stringname="test_html"><Data><![CDATA[<b><fontcolor="#ffcce2">"Str类型:"<xliff:gid="format">%1$s</xliff:g>
"\nInt类型:"<xliff:gid="format">%2$06d</xliff:g></font></b>]]></Data></string>
main.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextViewandroid:id="@+id/test_html"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
TestHtmlActivity.java:
packagecom.android.testhtml;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.text.Html;
importandroid.text.Spanned;
importandroid.widget.TextView;
publicclassTestHtmlActivityextendsActivity{
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
StringfirstVar="Hello,TestHtml";
intsecondVar=101;
setContentView(R.layout.main);
SpannedtestHtml=Html.fromHtml(getResources().getString(R.string.test_html,firstVar,secondVar));
((TextView)findViewById(R.id.test_html)).setText(testHtml);}
}
AndroidManifest.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.testhtml"
android:versionCode="1"
android:versionname="1.0">
<uses-sdkandroid:minSdkVersion="10"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".TestHtmlActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>