為 EditText 設定 OnFocusChangeListener,在 onFocusChange 中檢查 hasFocus 為 false 即表示失去焦點。
EditText editText = findViewById(R.id.edittxt);
editText.setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
// 失去焦點時執行:驗證輸入、隱藏鍵盤、儲存草稿等
validateInput(editText.getText().toString());
}
});
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0);requestFocus()),hasFocus 仍能正確反映。android:nextFocusDown 等屬性影響。