文字标签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五大布局。
相关文章
相关标签/搜索