programing

XML 형식의 html 형식 문자열 리소스에서 TextView 텍스트 설정

new-time 2020. 5. 12. 21:33
반응형

XML 형식의 html 형식 문자열 리소스에서 TextView 텍스트 설정


내 안에 고정 문자열이 있습니다

strings.xml

.

<resources>
    <string name="somestring">
        <B>Title</B><BR/>
        Content
    </string>
</resources>

그리고 내 레이아웃

TextView

에는 html 형식 문자열로 채우고 싶은 것이 있습니다.

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

이 작업을 수행하면 내용은 HTML 태그

formattedtext

somestring

제거되어 형식이 지정되지 않은 내용입니다.형식이 지정된 텍스트를 프로그래밍 방식으로 설정할 수 있음을 알고 있습니다.

.setText(Html.fromHtml(somestring));

프로그램의 다른 부분에서 예상대로 작동하기 때문에 이것을 사용하기 때문입니다.이 함수를 호출하려면을 필요로

Activity

하지만 현재 레이아웃은 일반 XML의 단순한 정적 뷰 일

Activity

뿐이며 일부를 설정하기 위한 오버 헤드를 피하기 위해 그런 식으로 두는 것이 좋습니다. 본문.내가 명백한 것을 내려다보고 있습니까? 전혀 가능하지 않습니까? 도움이나 해결 방법을 환영합니다!편집 : 그냥 몇 가지를 시도해 보았고 XML의 HTML 형식에는 약간의 제약이있는 것 같습니다.

  • 태그는 소문자로 작성해야합니다
  • 여기

    에 언급 된 일부 태그가 작동하지 않습니다

    <br/>

    ( 예 :

    \n

    대신 사용할 수 있음 )

누군가가 이것을 발견하면 문서화되지 않은 더 좋은 대안이 있습니다 (시간을 검색 한 후 넘어서 마침내 Android SDK 자체의 버그 목록에서 찾았습니다). 당신은

CAN

당신이 그것을 포장뿐만 strings.xml의 원시 HTML을 포함

<![CDATA[ ...raw html... ]]>

예:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

그런 다음 코드에서 :

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, 이것은 작업하기에 더 좋은 몇 가지 크기입니다 :-)


여기에 가장 좋은 대답은 잘못된 것을 제안하고

있거나 적어도 너무 복잡하기 때문에 질문이 꽤 오래되었지만 업데이트해야한다고 생각합니다.Android에서 문자열 리소스를

getString(...)

사용하는 경우 Java 코드에서 호출 하거나

android:text="@string/..."

레이아웃 XML에서 사용해야 합니다.

문자열에서 HTML 마크 업을 사용하려는 경우에도 크게 변경할 필요가 없습니다.

String 리소스에서 이스케이프해야하는 유일한 문자는 다음과 같습니다.

  • 큰 따옴표는 : "이된다\"
  • 작은 따옴표는 : '이된다\'
  • 앰퍼샌드 : &되고 &#38;또는&amp;

, 태그

를 이스케이프하지 않고 HTML 마크 업을

추가 할 수 있습니다 .

<string name="my_string"><b>Hello World!</b> This is an example.</string>

그러나, 확실하게, 당신은 단지 사용해야합니다

<b>

,

<i>

그리고

<u>

그들은 문서에 나열되어있다.

XML에서

HTML 문자열을 사용하려면 계속 사용

android:text="@string/..."

하면 정상적으로 작동합니다.유일한 차이점은

Java 코드에서

HTML 문자열 을 사용 하려면 전자가 스타일을 유지하고 후자는 그냥 제거하므로 지금

getText(...)

대신 사용해야 한다는 것입니다

getString(...)

.그렇게 쉽습니다. CDATA도 없습니다

Html.fromHtml(...)

.당신은해야합니다

Html.fromHtml(...)

당신이 경우

HTML 태그에 인코딩하여 특수 문자를.

getString(...)

그때 와 함께 사용하십시오 . String을로 전달하려는 경우에 필요할 수 있습니다

String.format(...)

.이것은 모두

문서에

설명 되어 있습니다.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

여기에 이미지 설명을 입력하십시오


Escape your HTML tags ...

<resources>
    <string name="somestring">
        &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt;
        Content
    </string>
</resources>

Android does not have a specification to indicate the type of resource string (e.g. text/plain or text/html). There is a workaround, however, that will allow the developer to specify this within the XML file.

  1. Define a custom attribute to specify that the android:text attribute is html.
  2. Use a subclassed TextView.

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. I'm rather surprised that this approach is not part of the API.

This solution works to the degree that the Android studio simulator will display the text as rendered HTML.

여기에 이미지 설명을 입력하십시오

res/values/strings.xml (the string resource as HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

Latest update:

Html.fromHtml(string);//deprecated after Android N versions..

Following code give support to android N and above versions...

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(yourHtmlString,Html.FROM_HTML_MODE_LEGACY));
}

else 
{
textView.setText(Html.fromHtml(yourHtmlString));
}

  String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
  String commma="<font color=#000000>, </font>";
  String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
  Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
        secondCheckBox.setText(text);

I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server.

Here is what I get from a server:

<p>The quick brown&nbsp;<br />
fox jumps&nbsp;<br />
 over the lazy dog<br />
</p>

It seems to be more complicated but the solution is much simpler.

private TextView textView;

protected void onCreate(Bundle savedInstanceState) { 
.....
textView = (TextView) findViewById(R.id.text); //need to define in your layout
String htmlFromServer = getHTMLContentFromAServer(); 
textView.setText(Html.fromHtml(htmlFromServer).toString());

}

Hope it helps!
Linh

참고URL : https://stackoverflow.com/questions/3235131/set-textview-text-from-html-formatted-string-resource-in-xml

반응형