MainActivity如下:
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); } }
Strings.xml如下:
<?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>
main.xml如下:
<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>