2010年4月8日星期四

Java格式字符串(Java Format String)

除了在字符串資源(String Resources)文章中提到簡單格式化的字符串外, Android也可使用Java格式的字符串(Java Format String).



在/res/values/文件夾下面, 創建XML文件定義字符串資源:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="jave_format_string">Hello %1$s, it's %2$s.</string>
</resources>


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/mystring"
/>
</LinearLayout>


Java源代碼
package com.AndroidString;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidString extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView myString = (TextView)findViewById(R.id.mystring);
myString.setText(String.format(getString(R.string.jave_format_string), "Android", "Java Format String"));

}
}




沒有留言:

發佈留言