Android 从 XML 格式的 html 格式字符串资源设置 TextView 文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3235131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set TextView text from html-formatted string resource in XML
提问by slup
I have some fixed strings inside my strings.xml
, something like:
我的 里面有一些固定的字符串strings.xml
,比如:
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
and in my layout I've got a TextView
which I'd like to fill with the html-formatted string.
在我的布局中,我有一个TextView
我想用 html 格式的字符串填充的。
<TextView android:id="@+id/formattedtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/htmlstring"/>
if I do this, the content of formattedtext
is just the content of somestring
stripped of any html tags and thus unformatted.
如果我这样做, 的内容formattedtext
只是somestring
剥离任何 html 标签的内容,因此未格式化。
I know that it is possible to set the formatted text programmatically with
我知道可以通过编程方式设置格式化文本
.setText(Html.fromHtml(somestring));
.setText(Html.fromHtml(somestring));
because I use this in other parts of my program where it is working as expected.
因为我在程序的其他部分使用它,它按预期工作。
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.
要调用这个函数,我需要一个Activity
,但目前我的布局只是一个简单的或多或少的纯 XML 静态视图,我更愿意保持这种方式,以免我创建一个Activity
只是为了设置一些文本。
Am I overlooking something obvious? Is it not possible at all? Any help or workarounds welcome!
我是否忽略了一些明显的东西?根本不可能吗?欢迎任何帮助或解决方法!
Edit: Just tried some things and it seems that HTML formatting in xml has some restraints:
编辑:刚刚尝试了一些东西,似乎 xml 中的 HTML 格式有一些限制:
tags must be written lowercase
some tags which are mentioned heredo not work, e.g.
<br/>
(it's possible to use\n
instead)
标签必须小写
这里提到的一些标签 不起作用,例如
<br/>
(可以\n
改用)
回答by Bitbang3r
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 CANinclude raw HTML in strings.xml, as long as you wrap it in
以防万一有人发现这一点,有一个更好的替代方案没有记录(我在搜索了几个小时后绊倒了它,最后在 Android SDK 本身的错误列表中找到了它)。您CAN包括在strings.xml中原始的HTML,只要你把它包装
<![CDATA[ ...raw html... ]]>
Example:
例子:
<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>
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 :-)
恕我直言,这是几个数量级更好的工作:-)
回答by caw
As the top answer here is suggesting something wrong(or at least too complicated), I feel this should be updated, although the question is quite old:
由于这里的最佳答案暗示了一些错误(或至少太复杂),我觉得这应该更新,尽管这个问题已经很老了:
When using String resources in Android, you just have to call getString(...)
from Java code or use android:text="@string/..."
in your layout XML.
在 Android 中使用 String 资源时,您只需getString(...)
从 Java 代码中调用或android:text="@string/..."
在您的布局 XML 中使用。
Even if you want to use HTML markup in your Strings, you don't have to change a lot:
即使您想在您的字符串中使用 HTML 标记,您也不必进行太多更改:
The only characters that you need to escape in your String resources are:
您需要在 String 资源中转义的唯一字符是:
- double quotation mark:
"
becomes\"
- single quotation mark:
'
becomes\'
- ampersand:
&
becomes&
or&
- 双引号:
"
变成\"
- 单引号:
'
变成\'
- &符号:
&
变成&
或&
That means you can add your HTML markup without escapingthe tags:
这意味着您可以在不转义标签的情况下添加HTML 标记:
<string name="my_string"><b>Hello World!</b> This is an example.</string>
However, to be sure, you should only use <b>
, <i>
and <u>
as they are listed in the documentation.
但是,可以肯定的是,您应该只使用<b>
,<i>
并且<u>
它们在文档中列出。
If you want to use your HTML strings from XML, just keep on using android:text="@string/..."
, it will work fine.
如果您想使用XML 中的 HTML 字符串,请继续使用android:text="@string/..."
,它会正常工作。
The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...)
instead of getString(...)
now, as the former keeps the style and the latter will just strip it off.
唯一的区别是,如果您想使用Java 代码中的HTML 字符串,则必须使用getText(...)
而不是getString(...)
now,因为前者保留样式,而后者只会将其剥离。
It's as easy as that. No CDATA, no Html.fromHtml(...)
.
就这么简单。没有 CDATA,没有Html.fromHtml(...)
。
You will only need Html.fromHtml(...)
if you didencode your special characters in HTML markup. Use it with getString(...)
then. This can be necessary if you want to pass the String to String.format(...)
.
您只需要Html.fromHtml(...)
,如果你没有在HTML标记编码的特殊字符。使用它getString(...)
。如果您想将字符串传递给String.format(...)
.
This is all described in the docsas well.
这也在文档中进行了描述。
Edit:
编辑:
There is no difference between getText(...)
with unescaped HTML (as I've proposed) or CDATA
sections and Html.fromHtml(...)
.
有什么区别getText(...)
与转义HTML(因为我已经提出),或CDATA
部分和Html.fromHtml(...)
。
See the following graphic for a comparison:
请参阅下图进行比较:
回答by ekawas
Escape your HTML tags ...
转义您的 HTML 标签...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
回答by Steven Spungin
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.
Android 没有规范来指示资源字符串的类型(例如 text/plain 或 text/html)。但是,有一种变通方法可以让开发人员在 XML 文件中指定这一点。
- Define a custom attribute to specify that the android:text attribute is html.
- Use a subclassed TextView.
- 定义自定义属性以指定 android:text 属性为 html。
- 使用子类 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.
一旦你定义了这些,你就可以在 xml 文件中用 HTML 表达你自己,而不必再次调用 setText(Html.fromHtml(...)) 。我很惊讶这种方法不是 API 的一部分。
This solution works to the degree that the Android studio simulator will display the text as rendered HTML.
此解决方案在一定程度上适用于 Android Studio 模拟器将文本显示为呈现的 HTML。
res/values/strings.xml (the string resource as HTML)
res/values/strings.xml(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)
layout.xml(仅相关部分)
Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.
声明自定义属性命名空间,并添加 android_ex:isHtml 属性。还可以使用 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)
res/values/attrs.xml(定义子类的自定义属性)
<resources>
<declare-styleable name="TextViewEx">
<attr name="isHtml" format="boolean"/>
<attr name="android:text" />
</declare-styleable>
</resources>
TextViewEx.java (the subclass of TextView)
TextViewEx.java(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();
}
}
}
回答by Ranjith Kumar
Latest update:
最新更新:
Html.fromHtml(string);
//deprecated after Android N versions..
Html.fromHtml(string);
//Android N 版本后弃用..
Following code give support to android N and above versions...
以下代码支持android N及以上版本...
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));
}
回答by Dishant Kawatra
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);
回答by Linh Lino
I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server.
我还有另一种情况,当我从服务器接收字符串 HTML 时,我没有机会将 CDATA 放入 xml 中。
Here is what I get from a server:
这是我从服务器得到的:
<p>The quick brown <br />
fox jumps <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
希望能帮助到你!
灵