android 资源文件string.xml字符支持HTML样式和格式

android developers上说的,string resource 不仅能定义字符串,还支持字符串的styling和formatting。

android 通过如下方法来定义字符串资源

字符串




    text_string

name 属性为该string的id。可通过 Activity的getString(id)的方法在代码中获得字符串的值。

字符串数组



    
        text_string
    

在代码里面可以这样获得字符串数组资源
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

字符串格式化
在字符串中出现单引号和双引号,不能直接写于xml中:
"This'll work"
This\'ll also work
This doesn't work
XML encodings don't work

在资源中定义的字符串同样支持格式化.
Hello, %1$s! You have %2$d new messages.
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

使用HTML标签


    Welcome to Android!


这样在TextView中”Android”会显示为粗体.

在代码中可以这样使用:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);

在文档中说支持的html标签,只有:



但是,Html.fromHtml(text)支持的html标签却不只这些,具体有那些android平台并没有详细列举.在  HTML Tags Supported By TextView  有详细列举.但是额外的标签不能直接定义在xml中.貌似会被过滤掉.所以使用额外的标签时,必须用包围住.当然这样的字符串就不能直接在xml中调用了.只能通过代码使用.
        %s
	    ]]>
    


你可能感兴趣的:(Android学习资料)