更改與顯示文字標籤TextView標籤的使

在Android初級教程(五)我們寫了HelloAndroid 之後,一直覺得沒有寫半行代碼對不起自己,所以本節,我們將在HelloAndroid 基礎之上,進行與TextView 文字標籤的第一次接觸.在此例中,將會在Layout 中創建TextView 對象,並學會定義res/values/string.xml 裏的字符串常數,最後通過TextView 的setText 方法,在預加載程序之初,更改TextView 文字.
首先看一下運行結果如下圖:

首先"歡迎來到魏祝林的博客"這幾個字是從什麼地方來的呢,我們是在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);
}
}
兩種方法都可以達到一樣的效果,不過我在此建議用第一種比較規範一點.這一節就到此爲至!!下一節我們將講一下Android五大布局.希望大家繼續關注~
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章