문자열 리소스의 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 (표시된 링크 포함)을 렌더링해야하는 경우 스팬 가능한 텍스트를 가져 오는 호출을 TextView수행해야 Html.fromHtml(...)합니다.


1
아니요, 펠릭스의 대답을 꼭 봐야합니다. CDATA는 필요하지 않습니다.
caw

4
@MarcoW. Felix의 대답은 사실이지만 CDATA를 사용하면 html 태그에 대해 걱정할 필요가 없습니다. 이 답은 정답이어야합니다.
slhddn

3
문자열에 링크가있는 경우 textView.setMovementMethod (LinkMovementMethod.getInstance ());를 추가하는 것을 잊지 마십시오.
Adarsh ​​Urs 2015 년

1
내가 사용했다 \"에 대한 style생각, 재산. 예<a style=\"...\">link</a>
Fabricio

1
CDATA는 HTML 태그로 문자열을 스타일링 할 때 훨씬 더 많은 유연성을 제공합니다. 그것이 100 %가는 길이라는 데 동의합니다!
Droid Chris

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>
뿐입니다

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
불행히도이 방법을 사용하여, 문자열 변수는 사용할 수 없습니다
알레산드로 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));당신은 차이를 볼 수 있습니다.


이 날 정말 도움이 답변 주셔서 감사합니다
Alsemany

매우 크고 복잡한 HTML 파일이 있어도?
Supuhstar

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