【攻占Android (7)】String格式化输出

【攻克Android (7)】String格式化输出
一、String格式化输出

        1. 字符串资源

        (1)String (字符串)

        在 strings.xml 中定义:

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
     <string name="hello">Hello!</string>  
 </resources>


        在布局文件中引用:

 <TextView  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="@string/hello" />


        在活动(Java类)中引用:

String string = getString(R.string.hello);



        (2)String Array (字符串数组)

        在 strings.xml 中定义:

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
     <string-array name="planets_array">  
         <item>Mercury</item>  
         <item>Venus</item>  
         <item>Earth</item>  
         <item>Mars</item>  
     </string-array>  
 </resources>


        在活动(Java类)中引用:

 Resources res = getResources();  
 String[] planets = res.getStringArray(R.array.planets_array);



        (3)Quantity String(Plurals) (数量字符串/复数)

        在 res/values/strings.xml 中定义:

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
     <plurals name="numberOfSongsAvailable">  
         <item quantity="one">One song found.</item>  
         <item quantity="other">%d songs found.</item>  
     </plurals>  
 </resources>


        在 res/values-pl/strings.xml 中定义:

 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
     <plurals name="numberOfSongsAvailable">  
         <item quantity="one">Znaleziono jedną piosenkę.</item>  
         <item quantity="few">Znaleziono %d piosenki.</item>  
         <item quantity="other">Znaleziono %d piosenek.</item>  
     </plurals>  
 </resources>


        在活动(Java类)中引用:

 int count = getNumberOfsongsAvailable();  
 Resources res = getResources();  
 String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);



        2. String格式化输出

        String.format("-----%s----%d", getString(R.string.hello_world), 200)

        String.format("%f----%.2f", Math.PI, Math.PI)