2022-10-22学习内容
1.文本变化监听器
1.1activity_edit_hide.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp"> <EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:hint="输入11位时自动隐藏输入法" android:inputType="text" android:background="@drawable/editext_selector" android:maxLength="11"/> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="@drawable/editext_selector" android:hint="输入6位时自动隐藏输入法" android:inputType="textPassword" android:maxLength="6"/> </LinearLayout>
1.2ViewUtil.java
package com.example.chapter05.util; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; public class ViewUnil { public static void hideOneInputMethod(Activity act, View v) { // 从系统服务中获取输入法管理器 InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE); // 关闭屏幕上的输入法软键盘 imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } }
1.3EditHideActivity.java
package com.example.chapter05; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import com.example.chapter05.util.ViewUnil; public class EditHideActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_hide); EditText et_phone = findViewById(R.id.et_phone); EditText et_password = findViewById(R.id.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; public HideTextWatcher(EditText v, int maxLength) { this.mView = v; this.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(); // 输入文本达到11位(如手机号),或者达到6位(如登录密码)时关闭输入法 if (str.length() == mMaxLength) { // 隐藏输入法软键盘 ViewUnil.hideOneInputMethod(EditHideActivity.this, mView); } } } }
1.4效果: