监听EditText的变化
使用EditText的addTextChangedListener(TextWatcher watcher)方法对EditText实现监听,TextWatcher是一个接口类,所以必须实现TextWatcher里的抽象方法:
当EditText里面的内容有变化的时候,触发TextChangedListener事件,就会调用TextWatcher里面的抽象方法。
MainActivity.java
1.package com.lingdududu.watcher;
2.
3.import Android.app.Activity;
4.import android.app.AlertDialog;
5.import android.content.DialogInterface;
6.import android.os.Bundle;
7.import android.text.Editable;
8.import android.text.TextWatcher;
9.import android.util.Log;
10.import android.widget.EditText;
11.
12.public class MainActivity extends Activity {
13. private EditText text;
14. String str;
15. @Override
16. public void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.main);
19.
20. text = (EditText)findViewById(R.id.text);
21. text.addTextChangedListener(textWatcher);
22. }
23.
24. private TextWatcher textWatcher = new TextWatcher() {
25.
26. @Override
27. public void afterTextChanged(Editable s) {
28. // TODO Auto-generated method stub
29. Log.d("TAG","afterTextChanged--------------->");
30. }
31.
32. @Override
33. public void beforeTextChanged(CharSequence s, int start, int count,
34. int after) {
35. // TODO Auto-generated method stub
36. Log.d("TAG","beforeTextChanged--------------->");
37. }
38.
39. @Override
40. public void onTextChanged(CharSequence s, int start, int before,
41. int count) {
42. Log.d("TAG","onTextChanged--------------->");
43. str = text.getText().toString();
44. try {
45. //if ((heighText.getText().toString())!=null)
46. Integer.parseInt(str);
47.
48. } catch (Exception e) {
49. // TODO: handle exception
50. showDialog();
51. }
52.
53. }
54. };
55.
56. private void showDialog(){
57. AlertDialog dialog;
58. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
59. builder.setTitle("消息").setIcon(android.R.drawable.stat_notify_error);
60. builder.setMessage("你输出的整型数字有误,请改正");
61. builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
62. @Override
63. public void onClick(DialogInterface dialog, int which) {
64. // TODO Auto-generated method stub
65.
66. }
67. });
68. dialog = builder.create();
69. dialog.show();
70. }
71.}
main.xml
1.<?xml version="1.0" encoding="utf-8"?>
2.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical"
4. android:layout_width="fill_parent"
5. android:layout_height="fill_parent"
6. >
7.<TextView
8. android:layout_width="fill_parent"
9. android:layout_height="wrap_content"
10. android:text="请输入整型数字