从XML HTML格式的字符串资源设置TextView的文本 [英] Set TextView text from html-formatted string resource in XML

查看:173
本文介绍了从XML HTML格式的字符串资源设置TextView的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我里面的一些固定的字符串我的的strings.xml ,是这样的:

I have some fixed strings inside my strings.xml, something like:

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

在我的布局我有一个的TextView ,我想,以填补与HTML格式的字符串。

and in my layout I've got a TextView which I'd like to fill with the html-formatted string.

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

如果我这样做,对内容formattedtext 是刚刚含量 somestring 剥夺任何HTML标记和从而格式化。

if I do this, the content of formattedtext is just the content of somestring stripped of any html tags and thus unformatted.

我知道这是可以用编程方式设置格式的文本

I know that it is possible to set the formatted text programmatically with

.setText(Html.fromHtml(somestring));

因为我用这个在我的计划在那里按预期工作等部位。

because I use this in other parts of my program where it is working as expected.

要调用这个函数,我需要一个活动,但此刻我的布局仅仅是一个简单的或多或少的静态视图纯XML和我最好preFER留下这样的说法,救我从创建活动只是设置一些文本的开销。

To call this function I need an Activity, but at the moment my layout is just a simple more or less static view in plain XML and I'd prefer to leave it that way, to save me from the overhead of creating an Activity just to set some text.

我俯瞰明显的东西?它是不可能的呢?任何帮助或解决方法欢迎!

Am I overlooking something obvious? Is it not possible at all? Any help or workarounds welcome!

编辑:只是尝试了一些东西,似乎在XML HTML格式有一定的限制:

Just tried some things and it seems that HTML formatting in xml has some restraints:

  • 标签必须用小写

  • tags must be written lowercase

这是这里提到一些标签不工作,例如: &LT; BR /&GT; (很可能使用代替)

some tags which are mentioned here do not work, e.g. <br/> (it's possible to use \n instead)

推荐答案

万一有人发现这一点,有一个更好的替代方案,不是记录(我在它绊倒搜寻了几个小时后,终于找到了在bug列表在Android SDK本身)。您可以包含原始的HTML中的strings.xml,只要你在

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

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

然后,在你的code:

Then, in your code:

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

恕我直言,这是更好级几个订单一起工作: - )

IMHO, this is several orders of magnitude nicer to work with :-)

这篇关于从XML HTML格式的字符串资源设置TextView的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆