Android中Strings.xml使用佔位符示例
阿新 • • 發佈:2019-01-28
轉自: http://www.2cto.com/kf/201308/232709.html
package cn.test; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 在資原始檔Strings.xml中的某個string裡使用佔位符 * 然後在程式碼中將其替換 */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ String stringStart=getResources().getString(R.string.stringStart); String startResult=String.format(stringStart, "佔位符的測試:"); System.out.println("startResult="+startResult); String stringTest=getResources().getString(R.string.stringTest); String stringResult=String.format(stringTest, "周星馳","香港",55); System.out.println("stringResult="+stringResult); String numberTest=getResources().getString(R.string.numberData); String numberResult=String.format(numberTest,9527,88.88f); System.out.println("numberResult="+numberResult); } }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">TestStringResource</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="stringStart">現在開始%1$s</string> <string name="stringTest">My name is %1$s , I am from %2$s,I am %3$d years old</string> <!-- .3f表示的是保留三位小數的浮點數 --> <string name="numberData">我的編號是(整數型):%1$d , 我的工資是(浮點型):%2$.3f</string> </resources>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="25sp" android:text="@string/hello_world" /> </RelativeLayout>