string.xml是一个字符串资源,为程序提供了可格式化和可选样式的字符串。
一般的字符串定义:
<string name="hello_kitty">Hello kitty</string> 资源引用在xml中:@string/hello_kitty在java中:R.string.hello_kitty一、当字符串有引号时<string name="good_example">"This'll work"</string> <string name="good_example_2">This\'ll also work</string> <string name="bad_example">This doesn't work</string> <string name="bad_example_2">XML encodings don't work</string> 如果字符串中有单引号,则要将整个字符串用双引号包起来,或者使用转义\'二、当字符串需要用String.format格式化时<string name="hello_kitty">Hello %1$s kitty</string> %1$s : 1表示占第一位,s表示字符串,d表示数字java代码:String format=String.format(R.string.hello_kitty,"your"); 三、当字符串有html标记时<b>kitty</b> 加粗<string name="hello_kitty">Hello <b>kitty</b></string> java代码:Resources res = getResources(); String kitty = res.getString(R.string.hello_kitty); //textView.setText(kitty); 四、当字符串又需要格式化,又有样式的时候<string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string> 上面是错误的写法,因为参考原文一段话In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the< notation.所以我们需要这么写<string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string> java代码:String format = String.format(res.getString(R.string.hello_kitty), "your"); Spanned html = Html.fromHtml(format); textView.setText(html); Html.fromHtml()会解析所有html标记,但如果String.format()的参数中有html标记但又不想被Html解析比如 <u>your</u>,就要对参数进行编码java代码:Resources res = getResources(); String encode = TextUtils.htmlEncode("<u>your</u>"); String format = String.format(res.getString(R.string.hello_kitty), encode); Spanned html = Html.fromHtml(format); tv1.setText(html); tip:Spanned html = Html.fromHtml(format); String htmlStr = Html.fromHtml(format).toString(); //有样式 tv1.setText(html); //无样式 tv2.setText(htmlStr); AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
AI代码助手复制代码
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。