简体   繁体   English

android 从字符串资源中获取文本

[英]android getText from string resource

In my app, I want to display a string in a text view with html markup.在我的应用程序中,我想在带有 html 标记的文本视图中显示一个字符串。 this will get the string:这将得到字符串:

String mystring = getResources().getString(R.string.Terms_And_Conditions);

except won't allow html characters.除了不允许 html 字符。 I can see on forums to use getText() instead but it doesn't work我可以在论坛上看到使用 getText() 但它不起作用

mystring = getResources().getText(R.string.Terms_And_Conditions);

I get the error我得到错误

error: incompatible types: CharSequence cannot be converted to String

In all the examples of using html in a text view, they just had a simple hard coded string, and that works fine.在文本视图中使用 html 的所有示例中,它们只有一个简单的硬编码字符串,而且效果很好。 But pulling the string from the resources, it just eats all the html, like the html tags aren't their, but also it didn't actually do the markup.但是从资源中提取字符串,它只是吃掉了所有 html 标签,但它实际上并没有做标记。 Everyone says I need to use getText() instead.每个人都说我需要改用 getText() 。 So how can I use getText() to get a string resource or how can I display the html in my string resource?那么如何使用 getText() 获取字符串资源,或者如何在我的字符串资源中显示 html? Or do I just have to hard code the string directly in Java?还是我只需要直接在 Java 中对字符串进行硬编码?

Thank you in advance.先感谢您。

If you want to use getText() you have to proceed like this:如果你想使用 getText() 你必须这样进行:

    String mystring = activity.getResources().getText(R.string.Terms_And_Conditions).toString()

To allow html characters, you can wrap the resource value in <.[CDATA[... ]]>要允许 html 字符,您可以将资源值包装在<.[CDATA[... ]]>

For example, if I want to display the string <button></button> :例如,如果我想显示字符串<button></button>

strings.xml:字符串。xml:

<string name="button_button"><![CDATA[<button></button>]]></string>

MainActivity.kt: MainActivity.kt:

val mystring:String = getResources().getText(R.string.button_button).toString();
Log.wtf("mystring", mystring)

Log output:日志 output:

E/mystring: <button></button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM