ric*_*hey 5 android string-formatting textview android-layout
当TextView元素以格式化形式显示文本时,我对"规则"感到有些困惑.
像一个字符串
"There are <i>different ways</i> of coding.\n";
Run Code Online (Sandbox Code Playgroud)
我编码时没有任何格式(包括HTML代码)显示
tvMyTextView.setText("There are <i>different ways</i> of coding.\n");
Run Code Online (Sandbox Code Playgroud)
但是当我在strings.xml中定义相同的字符串然后加载
tvMyTextView.setText(R.strings.TestString);
Run Code Online (Sandbox Code Playgroud)
它显示强调.
当我尝试在TextView中嵌入URL时,我觉得更加困惑:
"Click <a href="http://www.poon-world.com">here</a> to switch on the red light.\n";
Run Code Online (Sandbox Code Playgroud)
毋庸置疑,我已经尝试过TextView的各种属性选项 - 但除非我错过了一些东西,否则它们似乎没什么区别.在某些情况下,URL在文本中编码,蓝色并且可以单击,在其他情况下,我可以看到HTML格式.在其他人中,它是彩色编码的,并且URL似乎以某种方式在文本中编码 - 但是当我点击它时没有任何反应.关于URL的嵌入,与"简单"HTML格式化的另一个例子不同,到目前为止我甚至找不到一个规则,当它工作时和不工作时.任何人都可以帮我解开脑袋里的结.
实际上,来自Android Docs ..
public final void setText (CharSequence text)
Run Code Online (Sandbox Code Playgroud)
设置TextView的字符串值.TextView不接受类似HTML的格式,您可以使用XML资源文件中的文本字符串.要设置字符串样式,请将android.text.style.*对象附加到SpannableString,或者参阅可用资源类型文档以获取在XML资源文件中设置格式化文本的示例.
但,
public final void setText (int resid)
Run Code Online (Sandbox Code Playgroud)
但是从Android资源字符串文档..
您可以使用HTML标记为字符串添加样式.例如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="welcome">Welcome to <b>Android</b>!</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
支持的HTML元素包括:
<b> for bold text.
<i> for italic text.
<u> for underline text.
Run Code Online (Sandbox Code Playgroud)
有时您可能希望创建一个样式化的文本资源,该资源也用作格式字符串.通常,这不起作用,因为该String.format(String, Object...)方法将从字符串中删除所有样式信息.解决这个问题的方法是使用转义实体编写HTML标记,然后fromHtml(String)在格式化后进行恢复.
关于你的URL字符串,...
tvMyTextView.setText(Html.fromHtml("Click <a href="http://www.poon-world.com">here</a> to switch on the red light.\n"));
Run Code Online (Sandbox Code Playgroud)
另请参阅XML格式的html格式字符串资源中的 SO Question Set TextView文本
和
| 归档时间: |
|
| 查看次数: |
7222 次 |
| 最近记录: |