EditText监听器------实时监听

前言:

  在Android开发中EditText的使用频率还是挺高的,比如登录界面输入密码验证码等,有的时候要求我们要在输入号码后显示是哪家公司的,比如中国移动,中国联通,这是就会用到EditText监听器

正文:

  在xml文件中:

1 <EditText
2         android:layout_width="wrap_content"
3         android:layout_height="wrap_content"
4         android:hint="输入号码"
5         android:id="@+id/input1"/>

在Java文件中

使用addTextChangedListener方法和匿名内部类TextWatcher来添加EditText监听器,在这个监听器中我们要重写三个方法分别为

1 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
2 public void onTextChanged(CharSequence s, int start, int before, int count) {}
3 public void afterTextChanged(Editable s) {}
beforeTextChanged方法中
s:改变之前的文本
start:改变之前的文本数
count:被改变原有内容的数量
after:表示改变后新的内容的数量
onTextChanged方法中
s:为改变了的文本,如本来是12,我在输入3,此时s为123
count:表示新增的数量
before:被改变的数量
start:表示输入之前的数量
afterTextChanged方法中
s:为输入之后的文本
 1 import android.support.v7.app.AppCompatActivity;
 2 import android.os.Bundle;
 3 import android.text.Editable;
 4 import android.text.TextWatcher;
 5 import android.text.method.HideReturnsTransformationMethod;
 6 import android.text.method.PasswordTransformationMethod;
 7 import android.util.Log;
 8 import android.widget.CheckBox;
 9 import android.widget.CompoundButton;
10 import android.widget.EditText;
11 import android.widget.RadioButton;
12 import android.widget.RadioGroup;
13 import android.widget.Toast;
14 
15 public class MainActivity extends AppCompatActivity {
16     private CheckBox checkbox;
17     private EditText edittext;
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22         checkbox=(CheckBox)findViewById(R.id.checkbox);
23         edittext=(EditText)findViewById(R.id.input1);
24         edittext.addTextChangedListener(new TextWatcher() {
25             @Override
26             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
27 
28             }
29 
30             @Override
31             public void onTextChanged(CharSequence s, int start, int before, int count) {
32 
33             }
34 
35             @Override
36             public void afterTextChanged(Editable s) {
37                 if (edittext.getText().length() == 11) {
38                     Toast.makeText(MainActivity.this, "中国移动", Toast.LENGTH_LONG).show();
39                 }
40                 
41             }
42         });
43 
44 
45     }
46 }

上面代码是当输入11个数字时,提示中国移动

 

posted @ 2020-02-04 12:48  东功  阅读(2336)  评论(0编辑  收藏  举报