今天学edittext的焦点变更监听器和文本变更监听器

利用设置监听焦点变更来确认输入的电话号码是不是正确的形式

public class EditFocusActivity extends AppCompatActivity implements View.OnFocusChangeListener {

private EditText et_phone;
private EditText et_password;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_edit_focus);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});

et_phone = findViewById(R.id.et_phone);
et_password = findViewById(R.id.et_password);
et_password.setOnFocusChangeListener(this);
}

@Override
public void onFocusChange(View view, boolean b) {
if(hasWindowFocus()){
String phonenum = et_phone.getText().toString();
if(TextUtils.isEmpty(phonenum)||phonenum.length()<10 ){
et_phone.requestFocus();
Toast.makeText(this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
}
}
}
}

利用设置文本监听器使输入到正确的密码数量时 把键盘关掉

public class EditHideActivity extends AppCompatActivity {

private EditText et_password;
private EditText et_phone;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_edit_hide);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
et_phone = findViewById(R.id.et_phone);
et_password = findViewById(R.id.et_password);

et_phone.addTextChangedListener(new HideTextWatcher(et_phone,10));
et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
}

private class HideTextWatcher implements TextWatcher {

private EditText mView;
private int mMaxLength;

public HideTextWatcher(EditText etPhone, int maxLength) {
this.mView = etPhone;
this.mMaxLength = maxLength;
}

@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

}

@Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
if(str.length() == mMaxLength){
ViewUtil.hiadeOneInputMethod(EditHideActivity.this,mView);
}
}
}
}