文字標籤TextView的使用

咱們寫了HelloAndroid 以後,一直以爲沒有寫半行代碼對不起本身,因此本節,咱們將在HelloAndroid 基礎之上,進行與TextView 文字標籤的第一次接觸.在此例中,將會在Layout 中建立TextView 對象,並學會定義res/values/string.xml 裏的字符串常數,最後經過TextView 的setText 方法,在預加載程序之初,更改TextView 文字.

首先看一下運行結果以下圖:



首先"歡迎來到魏祝林的博客"這幾個字是從什麼地方來的呢,咱們是在res->values->string.xml裏面加了以下一句 (黑體):
java

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="hello">Hello World, HelloAndroid!</string>
  4.     <string name="app_name">HelloAndroid</string>
  5.     <string name="textView_text">歡迎來到魏祝林的博客</string>
  6. </resources>
複製代碼
而加載"歡迎來到魏祝林的博客"是在main.xml (定義手機佈局界面的)里加入的,以下面代碼,其中咱們閨將@string/hello 改爲了@string/textView_text .
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent"
  6.     >
  7. <TextView
  8.     android:layout_width="fill_parent"
  9.     android:layout_height="wrap_content"
  10.     android:text="@string/textView_text"
  11.     />
  12. </LinearLayout>
複製代碼
這樣咱們運行HelloAndroid.java時,手機畫面裏將顯示"歡迎來到魏祝林的博客"的歡迎界面,貌似咱們又是沒有寫代碼,只是在.xml加了一兩行搞定,對習慣了編程的同窗,感受有點不適應.其實在HelloAndroid.java寫代碼也能夠徹底達到同樣的效果.

在這裏咱們首先將main.xml迴歸到原樣在原樣的基礎上加上一行見下方(黑體行)這裏ID是爲了在Java類裏,找到TextView對象,而且能夠控制它:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent"
  6.     >
  7. <TextView

  8.     android:id="@+id/myTextView"
  9.     android:layout_width="fill_parent"
  10.     android:layout_height="wrap_content"
  11.     android:text="@string/hello"
  12.     />
  13. </LinearLayout>
複製代碼
在主程序HelloAndroid.java裏代碼以下:
  1. package com.android.test;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.widget.TextView;

  5. public class HelloAndroid extends Activity {
  6.   
  7.     private TextView myTextView;
  8.     public void onCreate(Bundle savedInstanceState) {
  9.         super.onCreate(savedInstanceState);
  10.         //載入main.xml Layout,此時myTextView:text爲hello
  11.         setContentView(R.layout.main);
  12.       
  13.         //使用findViewById函數,利用ID找到該TextView對象
  14.         myTextView = (TextView)findViewById(R.id.myTextView);
  15.         String welcome_mes = "歡迎來到魏祝林的博客";


  16.         //利用setText方法將TextView文字改變爲welcom_mes
  17.         myTextView.setText(welcome_mes);
  18.     }
  19. }
複製代碼
兩種方法均可以達到同樣的效果,不過我在此建議用第一種比較規範一點.這一節就到此爲至!!下一節咱們將講一下Android五大布局。
相關文章
相關標籤/搜索