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;
相關文章
相關標籤/搜索