string.xml字符串的格式化和样式(Formatting and Styling)

string.xml是一个字符串资源,为程序提供了可格式化和可选样式的字符串。html

通常的字符串定义:java

  
  
           
  
  
  1. <string name="hello_kitty">Hello kitty</string> 

资源引用ide

在xml中:@string/hello_kittythis

在java中:R.string.hello_kitty编码

1、当字符串有引号时spa

   
   
            
   
   
  1. <string name="good_example">"This'll work"</string> 
  2. <string name="good_example_2">This\'ll also work</string> 
  3. <string name="bad_example">This doesn't work</string> 
  4. <string name="bad_example_2">XML encodings don&apos;t work</string> 

若是字符串中有单引号,则要将整个字符串用双引号包起来,或者使用转义\'code

2、当字符串须要用String.format格式化时orm

    
    
             
    
    
  1. <string name="hello_kitty">Hello %1$s kitty</string> 

%1$s : 1表示占第一位,s表示字符串,d表示数字xml

java代码:htm

     
     
              
     
     
  1. String format=String.format(R.string.hello_kitty,"your"); 

3、当字符串有html标记时

<b>kitty</b> 加粗

      
      
               
      
      
  1. <string name="hello_kitty">Hello <b>kitty</b></string> 

java代码:

       
       
                
       
       
  1. Resources res = getResources(); 
  2. String kitty = res.getString(R.string.hello_kitty); 
  3. //textView.setText(kitty); 

4、当字符串又须要格式化,又有样式的时候

        
        
                 
        
        
  1. <string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string> 

上面是错误的写法,由于参考原文一段话

In this formatted string, a  element is added. Notice that the opening bracket is HTML-escaped, using the notation.

因此咱们须要这么写

         
         
                  
         
         
  1. <string name="hello_kitty">&lt;i>Hello&lt;/i>&lt;b> %1$s kitty&lt;/b>!</string> 

java代码:

          
          
                   
          
          
  1. String format = String.format(res.getString(R.string.hello_kitty), 
  2.                 "your"); 
  3.         Spanned html = Html.fromHtml(format); 
  4. textView.setText(html); 

Html.fromHtml()会解析全部html标记,但若是String.format()的参数中有html标记但又不想被Html解析

好比 <u>your</u>,就要对参数进行编码

java代码:

            
            
                     
            
            
  1. Resources res = getResources(); 
  2. String encode = TextUtils.htmlEncode("<u>your</u>"); 
  3. String format = String.format(res.getString(R.string.hello_kitty), 
  4.                 encode); 
  5. Spanned html = Html.fromHtml(format); 
  6. tv1.setText(html); 

tip:

             
             
                      
             
             
  1. Spanned html = Html.fromHtml(format); 
  2. String htmlStr = Html.fromHtml(format).toString(); 
  3.          
  4. //有样式 
  5. tv1.setText(html); 
  6. //无样式 
  7. tv2.setText(htmlStr); 

<b>&lt;
相关文章
相关标签/搜索