之前的有關EditText的文章,只是介紹EditText的一些最基本的用法,這次來深入學習一下EditText。
監聽EditText的變化
使用EditText的addTextChangedListener(TextWatcher watcher)方法對EditText實現監聽,TextWatcher是一個接口類,所以必須實現TextWatcher裡的抽象方法:
650) this.width=650;">
當EditText裡面的內容有變化的時候,觸發TextChangedListener事件,就會調用TextWatcher裡面的抽象方法。
MainActivity.java
- package com.lingdududu.watcher;
- import Android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.text.Editable;
- import android.text.TextWatcher;
- import android.util.Log;
- import android.widget.EditText;
- public class MainActivity extends Activity {
- private EditText text;
- String str;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text = (EditText)findViewById(R.id.text);
- text.addTextChangedListener(textWatcher);
- }
- private TextWatcher textWatcher = new TextWatcher() {
- @Override
- public void afterTextChanged(Editable s) {
- // TODO Auto-generated method stub
- Log.d("TAG","afterTextChanged--------------->");
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count,
- int after) {
- // TODO Auto-generated method stub
- Log.d("TAG","beforeTextChanged--------------->");
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before,
- int count) {
- Log.d("TAG","onTextChanged--------------->");
- str = text.getText().toString();
- try {
- //if ((heighText.getText().toString())!=null)
- Integer.parseInt(str);
- } catch (Exception e) {
- // TODO: handle exception
- showDialog();
- }
- }
- };
- private void showDialog(){
- AlertDialog dialog;
- AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
- builder.setTitle("消息").setIcon(android.R.drawable.stat_notify_error);
- builder.setMessage("你輸出的整型數字有誤,請改正");
- builder.setPositiveButton("確定", new DialogInterface.OnClickListener(){
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // TODO Auto-generated method stub
- }
- });
- dialog = builder.create();
- dialog.show();
- }
- }
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"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="請輸入整型數字"
- />
- <EditText
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
效果圖:
當我們在輸入框輸入不是整型數字的時候,會立刻彈出輸入框,提示你改正
650) this.width=650;" height=310>