android 文本变化监听器

1.关闭软键盘

public static void hideOneInputMethod(Activity act, View v) {
// 从系统服务中获取输入法管理器
InputMethodManager imm = (InputMethodManager)
act.getSystemService(Context.INPUT_METHOD_SERVICE);
// 关闭屏幕上的输入法软键盘
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

注意:代码里面的视图对象v,虽然控件类型为View,但它必须是EditView类型才能正常关闭软键盘。

2.文本监听器接口TextWatcher,该接口提供了3个监听方法:

beforeTextChanged:在文本改变之前触发。

onTextChanged:在文本改变过程中触发。

afterTextChanged:在文本改变之后触发

案例:

<EditText
        android:id="@+id/et_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="请输入11时自动隐藏输入法"
        android:inputType="text"
        android:maxLength="11"
        android:background="@drawable/edit_selector9"/>
    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="请输入6时自动隐藏输入法"
        android:inputType="numberPassword"
        android:maxLength="6"
        android:background="@drawable/edit_selector9"/>

        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
//        给et_phone,et_password  添加文本变化监听器
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone,11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
    // 定义一个编辑框监听器,在输入文本达到指定长度时自动隐藏输入法
   private  class HideTextWatcher implements TextWatcher{
        private EditText mView; //编辑框对象
        private int mMaxLength; //最大长度
        private HideTextWatcher(EditText v, int maxLength){
            super();
            mView = v;
            mMaxLength = maxLength;
        }
        //编辑框的输入文本变化前触发
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {

       }
        //在编辑框的输入文本变化时触发
       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {

       }
        //在编辑框的输入文本变化后触发
       @Override
       public void afterTextChanged(Editable s) {
            String str = s.toString(); //获得已输入的文本
//          if((str.length() == 11 && mMaxLength == 11)|| (str.length() == 6 && mMaxLength ==6)){
            if (str.length() == mMaxLength){
               ViewUtil.hideOneInputMethod(edit_hide11.this, mView);
           }
       }
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

当当2000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值