首先我們是在res->values->string.xml里面加了如下一句(黑體):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloAndroid</string>
<string name="app_name">HelloAndroid</string>
<string name="textView_text">歡迎來到博客</string>
</resources>
而加載"歡迎來到博客"是在main.xml (定義手機布局界面的)里加入的,如下面代碼,其中我們閨將@string/hello 改成了@string/textView_text .
<?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/textView_text" /> </LinearLayout>
這樣我們運行HelloAndroid.java時,手機畫面里將顯示"歡迎來到博客"的歡迎界面,貌似我們又是沒有寫代碼,只是在.xml加了一兩行搞定,對習慣了編程的同學,感覺有點不適應.其實在HelloAndroid.java寫代碼也可以完全達到一樣的效果.
在這里我們首先將main.xml回歸到原樣在原樣的基礎上加上一行見下方(黑體行)這里ID是為了在Java類里,找到TextView對象,并且可以控制它:
<?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:id="@+id/myTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>
在主程序HelloAndroid.java里代碼如下:
package com.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
private TextView myTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //載入main.xml Layout,此時myTextView:text為hello
setContentView(R.layout.main); //使用findViewById函數,利用ID找到該TextView對象
myTextView = (TextView)findViewById(R.id.myTextView);
String welcome_mes = "歡迎來到博客"; //利用setText方法將TextView文字改變為welcom_mes
myTextView.setText(welcome_mes);
}
}