在Android初級(jí)教程(五)我們寫了 HelloAndroid 之后,一直覺得沒有寫半行代碼對(duì)不起自己,所以本節(jié),我們將在 HelloAndroid 基礎(chǔ)之上,進(jìn)行與 TextView 文字標(biāo)簽的第一次接觸.在此例中,將會(huì)在 Layout 中創(chuàng)建 TextView 對(duì)象,并學(xué)會(huì)定義 res/values/string.xml 里的字符串常數(shù),最后通過 TextView 的 setText 方法,在預(yù)加載程序之初,更改 TextView 文字.
首先看一下運(yùn)行結(jié)果如下圖:
首先"歡迎來到魏祝林的博客"這幾個(gè)字是從什么地方來的呢,我們是在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">歡迎來到魏祝林的博客</string>
</resources>
而加載"歡迎來到魏祝林的博客"是在 main.xml (定義手機(jī)布局界面的)里加入的,如下面代碼,其中我們閨將 @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>
這樣我們運(yùn)行HelloAndroid.java時(shí),手機(jī)畫面里將顯示"歡迎來到魏祝林的博客"的歡迎界面,貌似我們又是沒有寫代碼,只是在.xml加了一兩行搞定,對(duì)習(xí)慣了編程的同學(xué),感覺有點(diǎn)不適應(yīng).其實(shí)在HelloAndroid.java寫代碼也可以完全達(dá)到一樣的效果.
在這里我們首先將main.xml回歸到原樣在原樣的基礎(chǔ)上加上一行見下方(黑體行)這里ID是為了在Java類里,找到TextView對(duì)象,并且可以控制它:
<?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函數(shù),利用ID找到該TextView對(duì)象
myTextView = (TextView)findViewById(R.id.myTextView);
String welcome_mes = "歡迎來到魏祝林的博客";
//利用setText方法將TextView文字改變?yōu)閣elcom_mes
myTextView.setText(welcome_mes);
}
}
兩種方法都可以達(dá)到一樣的效果,不過我在此建議用第一種比較規(guī)范一點(diǎn).這一節(jié)就到此為至!!下一節(jié)我們將講一下Android五大布局.希望大家繼續(xù)關(guān)注~
Android基礎(chǔ)教程(一)之------更改與顯示文字標(biāo)簽TextView標(biāo)簽的使用
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
