program tip

문자열 리소스의 HTML?

radiobox 2020. 7. 26. 12:49
반응형

문자열 리소스의 HTML?


이스케이프 된 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). 왜 그런 겁니까? 태그와 모든 것이 포함 된 원본 문자열을 어떻게 얻을 수 있습니까? 주소록 애플리케이션은 어떻게 작동합니까?


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 (...) 호출을 수행해야합니다.


문자열을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>

가장 좋은 솔루션은 다음과 같은 방식으로 리소스를 사용하는 것입니다.

<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))와 함께 또는없이 해당 리소스를 사용하십시오. 그리고 당신은 차이를 볼 수 있습니다.


아이디어 : 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;
    }
}

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

참고 URL : https://stackoverflow.com/questions/2667319/html-in-string-resource

반응형