文字列リソース内のHTML?


120

エスケープされたHTMLタグを文字列リソースに配置できることはわかっています。ただし、連絡先アプリケーションのソースコードを見ると、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)。何故ですか?タグなどすべてを含む元の文字列を取得するにはどうすればよいですか?連絡先アプリケーションはどのように実行していますか?

回答:


199

また、htmlをCDATAブロックで囲むこともできgetString()、実際のHTMLを返します。そのような:

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

getString(R.string.foo)文字列を実行すると、文字列はHTMLになります。クリッカブルを介してHTMLを(リンクを表示して)レンダリングする必要がある場合はTextViewHtml.fromHtml(...)呼び出しを実行してスパン可能なテキストを取得する必要があります。


1
いいえ、間違いなくFelixの答えが表示されます。CDATAは必要ありません。
CAW

4
@MarcoW。Felixの答えは真実ですが、CDATAを使用すると、htmlタグを気にする必要がなくなります。この答えは正解でなければなりません。
slhddn 14

3
文字列にリンクがある場合は、忘れずにtextView.setMovementMethod(LinkMovementMethod.getInstance());を追加してください。
Adarsh Urs

1
しかし、私は財産の\"ために使わなければなりstyleませんでした。例<a style=\"...\">link</a>
2016年

1
CDATAを使用すると、HTMLタグで文字列をスタイリングする際の柔軟性が大幅に向上します。それが100%の道だと私は同意します!
ドロイドクリス

89

それ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>

28
:のみサポートされているタグは、<B>、<I>、<U>であることをしてくださいノートdeveloper.android.com/guide/topics/resources/...
Snicolas

2
@pawegio確かに意味\nですか?
Felix

7
@Snicolas:ドキュメントで言及されている3つ以上のタグをサポートしています:<b>、<i>、<u>、<big>、<small>、<sup>、<sub>、<strike>、 <li>、<marquee>、<a>、<font>および<annotation>(github.com/android/platform_frameworks_base/blob/…を参照)
rve

1
残念ながら、この方法を使用すると、文字列内の変数は許可されません
Alessandro Muzzi

1
<font>はapi23でサポートされていますが、api10ではサポートされていません。
illusionJJ

54

最善の解決策は、リソースを次のように使用することです。

<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);

なくても、そのリソースを使用しよう<![CDATA[ ]]>としてtv.setText(getText(R.string.htmlsource));、あなたは違いが表示されます。


この回答に感謝しますこれは本当に
役に立ち

非常に大きく複雑なHTMLファイルを使用している場合でも、
Supuhstar 2016

これは<font>タグをサポートしていますか?
Rohit Singh

1

これは古い質問ですが、最も効率的な回答はまだ提案されていないようです。

HTML-escaped処理されないように文字を使用してください。getStringただし、処理されるのはHtmlCompact.fromHtml(またはそれ以前のHtml.fromHtml)です。

これは、getStringメソッドのような書式設定だけでなく、HTMLリンクなどのより多くのタグもサポートします。

たとえば、次のようなものが機能するはずです。

<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>

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"
    />

-1

アイデア: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;
    }
}

それは少し過剰に設計されているようです、jsonではなくhtmlで保存してみませんか?
Misca
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.