接上次的教程,這次我們在介面中加個EditText,EditText是什麼?看名字就知道啦,什麼?你小學英語沒學好,我暈,Edit是編輯的意思,Text是文本,連一起就是可編輯文本控制項.我們看一下main.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"><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/editText"></EditText><Button android:layout_width="match_parent"android:layout_height="wrap_content" android:text="按鈕" android:id="@+id/button"></Button><TextView android:layout_height="wrap_content"android:layout_width="fill_parent" android:text="@string/hello"android:id="@+id/text"></TextView></LinearLayout>
接著就是Activity中的代碼了:
import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class ButtonDemoActivity extends Activity implements OnClickListener{private TextView text = null;private EditText edit_text = null;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// 通過ID尋找到main.xml中的TextView控制項text = (TextView) findViewById(R.id.text);// 通過ID尋找到main.xml中的EditText控制項edit_text = (EditText)findViewById(R.id.editText);// 通過ID尋找到main.xml中的Button控制項Button button = (Button) findViewById(R.id.button);// 為Button控制項增加單擊監聽器button.setOnClickListener(this);}/** * 對main.xml中所有控制項進行單擊監聽,當然您必須要對控制項進行監聽註冊 * 例:button.setOnClickListener(this); */@Overridepublic void onClick(View v){updateText();}private void updateText(){//取得EditText中輸入的文本資訊String edit_str = edit_text.getText().toString();//將文本資訊設定給TextView控制項顯示出來text.setText(edit_str);}}
我們這次增加一點,OK,寫完了,還是來運行一下,是不是輸入的資訊點擊按鈕都會顯示出來,很有趣吧?什麼?不能運行?那肯定是哪裡寫錯了,你再查看查看(look,look).呵呵,寫到這裡你一定認為寫完了,OH,NO,我們還需要再加點資訊.也很簡單,我們要對輸入的資訊做點判斷,你不能什麼也不輸吧?總得輸點東西才有看頭啊!
將最底下的updateText()改一下呢,代碼如下:
private void updateText(){// 取得EditText中輸入的文本資訊String edit_str = edit_text.getText().toString();if (edit_str.trim().length() == 0){text.setText("你可什麼都沒輸啊?想叫我顯示什麼呢?");} else{// 將文本資訊設定給TextView控制項顯示出來text.setText(edit_str);}}
OK,好了,這篇教程就結束了,EditText控制項也很簡單吧,這可是很重要的控制項哦,記住了!