更改与显示文字标签----android 2.2

来源:互联网 发布:玩客云官网抢购软件 编辑:程序博客网 时间:2024/04/25 19:04

此例子中,将会在Layout中创建TextView对象,并学会定义res/values/string.xml里的字符串常量,最后通过TextView的setText方法,在预加载程序之初,更改TextView文字。

程序:

1、按照hello android的方法,新建一个工程。

2、res/values/string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ex03_01!</string>
    <string name="str_1">Hello World, ex03_01!</string>
    <string name="app_name">ex03_01</string>
</resources>

3、res/layout/main.xml

以android:id命名TextView的ID为myTextView01;以android:text命名TextView的text为的值为字符串常量str_1.

<?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/myTextView01"
    android:text="@string/str_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="61px"
    android:layout_marginTop="69px"
    />

</LinearLayout>

4、src/irdc.ex03_01/ex03_01.java

主程序示范以setText方法,输出String类型的字符串变量

package irdc.ex03_01;

import android.app.Activity;
import android.os.Bundle;
//引用类
import android.widget.TextView;//add by christina 20101027

public class ex03_01 extends Activity {
 //声明对象
        private TextView mTextView01;  //add by christina 20101028
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*载入main.xml Layout,此时myTextView01:text为str_1*/
        setContentView(R.layout.main);
       
        /*使用findViewBtId函数,利用ID找到该TextView对象*/
        mTextView01=(TextView)findViewById(R.id.myTextView01);
        String str_2="欢迎来到Android 的TextView世界....";
        mTextView01.setText(str_2);
    }
}

 

运行结果