Android基础教程(一)之------更改与显示文字标签TextView标签的使用
在Android入门教程(五)我们写了HelloAndroid之后,一直觉得没有写半行代码对不起自己,对不起大家,更对不起人民,所以本节,我们将在HelloAndroid基础之上,进行与TextView文字标签的第一次接触.在此例中,将会在Layout中创建TextView对象,并学会定义res/values/string.xml里的字符串常数,最后通过TextView的setText方法,在预加载程序之初,更改TextView文字.
首先看一下运行结果如下图:
首先"欢迎来到火山哥的博客"这几个字是从什么地方来的呢,我们是在res->values->string.xml里面进行了修改:
<?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/hello" /> </LinearLayout>
倒数第三行android:text="@string/hello"这一句就是对string.xml文件名为name的引用,以键值对的方式存在。
那么如何在程序中更改它的显示呢?
第一,为这个TextView加上一个ID
<?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/mTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>第二,在程序中得到这个ID
第三,使用setText()方法
package org.sunchao;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView mTextView = (TextView) findViewById(R.id.mTextView);
mTextView.setText("文字已经改变了哦");
}
}运行效果如下: