在A(yíng)ndroid初級教程(五)我們寫(xiě)了HelloAndroid 之后,一直覺(jué)得沒(méi)有寫(xiě)半行代碼對不起自己,所以本節,我們將在HelloAndroid 基礎之上,進(jìn)行與TextView 文字標簽的第一次接觸.在此例中,將會(huì )在Layout 中創(chuàng )建TextView 對象,并學(xué)會(huì )定義res/values/string.xml 里的字符串常數,最后通過(guò)TextView 的setText 方法,在預加載程序之初,更改TextView 文字.
首先看一下運行結果如下圖:
首先"歡迎來(lái)到魏祝林的博客"這幾個(gè)字是從什么地方來(lái)的呢,我們是在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">歡迎來(lái)到魏祝林的博客</string>
- </resources>
而加載"歡迎來(lái)到魏祝林的博客"是在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時(shí),手機畫(huà)面里將顯示"歡迎來(lái)到魏祝林的博客"的歡迎界面,貌似我們又是沒(méi)有寫(xiě)代碼,只是在.xml加了一兩行搞定,對習慣了編程的同學(xué),感覺(jué)有點(diǎn)不適應.其實(shí)在HelloAndroid.java寫(xiě)代碼也可以完全達到一樣的效果.
在這里我們首先將main.xml回歸到原樣在原樣的基礎上加上一行見(jiàn)下方(黑體行)這里ID是為了在Java類(lèi)里,找到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,此時(shí)myTextView:text為hello
- setContentView(R.layout.main);
- //使用findViewById函數,利用ID找到該TextView對象
- myTextView = (TextView)findViewById(R.id.myTextView);
- String welcome_mes = "歡迎來(lái)到魏祝林的博客";
- //利用setText方法將TextView文字改變?yōu)閣elcom_mes
- myTextView.setText(welcome_mes);
- }
- }
兩種方法都可以達到一樣的效果,不過(guò)我在此建議用第一種比較規范一點(diǎn).這一節就到此為至!!下一節我們將講一下Android五大布局.希望大家繼續關(guān)注~
本文出自 “Android_Tutor” 博客,請務(wù)必保留此出處http://weizhulin.blog.51cto.com/1556324/311488
聯(lián)系客服