日期:2014-05-17  浏览次数:20747 次

在Android中使用html
string.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="hello">Hello World, TestHtmlActivity!</string>
    <string name="app_name">"TestHtml"</string>
<string name="test_html"><Data><![CDATA[ <b><font color="#ffcce2">"Str类型:"<xliff:g id="format">%1$s</xliff:g>
    "\n  Int类型:"<xliff:g id="format">%2$d</xliff:g></font></b> ]]></Data></string>
</resources>

注:<xliff:g id="format">%2$d</xliff:g>中的%2$d的字符含义如下:
%2:表示在源码中的第一个参数,$d表示该参数为整形,如果是$60d,则表示该整形必须为6位,如果传进的参数不足六位,如传递的是100,则会以0补足六位,得到的结果将是000100 。
可以这样定义string,如:<string name="test_html"><Data><![CDATA[ <b><font color="#ffcce2">"Str类型:"<xliff:g id="format">%1$s</xliff:g>
    "\n  Int类型:"<xliff:g id="format">%2$06d</xliff:g></font></b> ]]></Data></string>



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

    <TextView android:id="@+id/test_html"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>


TestHtmlActivity.java:
package com.android.testhtml;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;

public class TestHtmlActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String firstVar = "Hello, Test Html";
int secondVar = 101;
setContentView(R.layout.main);
Spanned testHtml = Html.fromHtml(getResources().getString(R.string.test_html, firstVar, secondVar));
((TextView) findViewById(R.id.test_html)).setText(testHtml);
}
}

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.testhtml"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TestHtmlActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

          &n