当用户将焦点从 edittext 更改为另一个项目时,我想更新 EditText 我想检查 edittext 的内容,例如大于 10 的数字,如果将其更改为 10。
我该怎么做。
设置setOnFocusChangeListener
为您的编辑文本...
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
//this if condition is true when edittext lost focus...
//check here for number is larger than 10 or not
editText.setText("10");
}
}
});
EditText ET =(EditText)findViewById(R.id.yourtextField);
ET.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean arg1) {
String myText = ET.getText();
//Do whatever
}
如果有人想在 kotlin 中使用数据绑定来执行此操作,请参考以下代码
//first get reference to your edit text
var editText:EditText = viewDataBinding.editText
// add listner on edit text
editText.setOnFocusChangeListener { v, hasFocus ->
if(!hasFocus)
{
if((editText.text.toString().toIntOrNull()>10)
{// add any thing in this block
editText.text = "10"
}
}
}
如果您有兴趣,我已经在这篇文章中进行了解释。去看看https://medium.com/@mdayanc/how-to-use-on-focus-change-to-format-edit-text-on-android -工作室-bf59edf66161
这是使用 OnFocusChangeListener 的简单代码
EditText myEditText = findViewById(R.id.myEditText);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
{
//Do something when EditText has focus
}
else{
// Do something when Focus is not on the EditText
}
}
});