咱們寫了HelloAndroid 以後,一直以爲沒有寫半行代碼對不起本身,因此本節,咱們將在HelloAndroid 基礎之上,進行與TextView 文字標籤的第一次接觸.在此例中,將會在Layout 中建立TextView 對象,並學會定義res/values/string.xml 裏的字符串常數,最後經過TextView 的setText 方法,在預加載程序之初,更改TextView 文字.
首先看一下運行結果以下圖:
首先"歡迎來到魏祝林的博客"這幾個字是從什麼地方來的呢,咱們是在res->values->string.xml裏面加了以下一句 (黑體): java
- <?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五大布局。