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);
}
}
}