字符串资源中的HTML?

时间:2010-04-19 12:26:26

标签: android

我知道我可以将转义的HTML标记放在字符串资源中。但是,查看Contacts应用程序的源代码,我可以看到他们有一种不必编码HTML的方法。引用联系人应用程序strings.xml

<string name="contactsSyncPlug"><font fgcolor="#ffffffff">Sync your Google contacts!</font> 
\nAfter syncing to your phone, your contacts will be available to you wherever you go.</string>

不幸的是,当我尝试类似的东西(例如Hello, <b>World</b>!)时,getString()会返回没有标记的字符串(我可以在logcat中看到)。这是为什么?如何获得带有标签和所有内容的原始字符串?联系人应用程序如何执行此操作?

6 个答案:

答案 0 :(得分:172)

您也可以在CDATA块中包围html,getString将返回您的实际HTML。像这样:

<string name="foo"><![CDATA[Foo Bar <a href="foo?id=%s">baz</a> is cool]]></string>

现在,当您执行getString(R.string.foo)时,字符串将是HTML。如果需要通过可点击的TextView呈现HTML(带有如图所示的链接),则需要执行Html.fromHtml(...)调用以获取可跨越文本。

答案 1 :(得分:83)

似乎getString()就是这样 - 获取字符串。要使用此功能,您必须使用getText()(并且不再需要Html.fromHtml()),即:

mTextView.setText(getText(R.string.my_styled_text));

然而,似乎android:text属性做同样的事情,以下是等价的:

<TextView android:text="@string/my_styled_text" />

strings.xml

<string name="my_styled_text">Hello, <b>World</b>!</string>

答案 2 :(得分:47)

最佳解决方案是以某种方式使用资源:

<string name="htmlsource"><![CDATA[<p>Adults are spotted gold and black on the crown, back and wings. Their face and neck are black with a white border; they have a black breast and a dark rump. The legs are black.</p><p>It is similar to two other golden plovers, Eurasian and Pacific. <h1>The American Golden Plover</h1> is smaller, slimmer and relatively longer-legged than Eurasian Golden Plover (<i>Pluvialis apricaria</i>) which also has white axillary (armpit) feathers. It is more similar to Pacific Golden Plover (<i>Pluvialis fulva</i>) with which it was once <b>considered</b> conspecific under the name \"Lesser Golden Plover\". The Pacific Golden Plover is slimmer than the American species, has a shorter primary projection, and longer legs, and is usually yellower on the back.</p><p>These birds forage for food on tundra, fields, beaches and tidal flats, usually by sight. They eat insects and crustaceans, also berries.</p>]]></string>

并显示:

Spanned sp = Html.fromHtml( getString(R.string.htmlsource));
tv.setText(sp);

尝试在没有和使用tv.setText(getText(R.string.htmlsource))的情况下使用该资源;你会发现差异。

答案 3 :(得分:2)

我知道这是一个古老的问题,但似乎尚未提出最有效的答案。

只需使用HTML-escaped个字符,这样它就不会被getString处理,而是会被HtmlCompact.fromHtml(或更旧的Html.fromHtml)处理。

这还支持更多的标记(例如HTML链接等),不仅支持getString方法的格式。

例如,类似这样的方法应该起作用:

<string name="html_message">Hello &lt;b>World&lt;/b>.</string>

val text = getString(R.string.html_message)
val result = HtmlCompact.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY)

在您的情况下,您将<替换为&lt;,如下所示:

<string name="contactsSyncPlug">&lt;font fgcolor="#ffffffff">Sync your Google contacts!&lt;/font> \nAfter syncing to your phone, your contacts will be available to you wherever you go.</string>

答案 4 :(得分:0)

想法:将HTML放在JSON格式的文件中并将它们存储在/ res / raw中。 (JSON不那么挑剔)

将这样的数据记录存储在数组对象中:

[
    {
        "Field1": "String data",
        "Field2": 12345,
        "Field3": "more Strings",
        "Field4": true
    },
    {
        "Field1": "String data",
        "Field2": 12345,
        "Field3": "more Strings",
        "Field4": true
    },
    {
        "Field1": "String data",
        "Field2": 12345,
        "Field3": "more Strings",
        "Field4": true
    }
]

要阅读应用中的数据:

private ArrayList<Data> getData(String filename) {
    ArrayList<Data> dataArray = new ArrayList<Data>();

    try {
        int id = getResources().getIdentifier(filename, "raw", getPackageName());
        InputStream input = getResources().openRawResource(id);
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        String text = new String(buffer);

        Gson gson = new Gson();
        Type dataType = new TypeToken<List<Map<String, Object>>>() {}.getType();
        List<Map<String, Object>> natural = gson.fromJson(text, dataType);

        // now cycle through each object and gather the data from each field
        for(Map<String, Object> json : natural) {
            final Data ad = new Data(json.get("Field1"), json.get("Field2"),  json.get("Field3"), json.get("Field4"));
            dataArray.add(ad);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return dataArray;
}

最后,Data类只是公共变量的容器,便于访问......

public class Data {

    public String string;
    public Integer number;
    public String somestring;
    public Integer site;
    public boolean logical;


    public Data(String string, Integer number, String somestring, boolean logical)
    {
        this.string = string;
        this.number = number;
        this.somestring = somestring;
        this.logical = logical;
    }
}

答案 5 :(得分:0)

没有CDATA阻止它对我有用。

<string name="menu_item_purchase" translatable="false"><font color="red">P</font><font color="orange">r</font><font color="yellow">e</font><font color="green">m</font><font color="white">i</font><font color="blue">u</font><font color="purple">m</font></string>`enter code here`

我在布局中使用它。

<item
    android:id="@+id/nav_premium"
    android:icon="@drawable/coins"
    android:title="@string/menu_item_purchase"
    />