I want to update an EditText when a user changes focus from the edittext to another item I want to check the contents of the edittext eg is the number larger than 10 if so change it to 10.
How should I do this.
I want to update an EditText when a user changes focus from the edittext to another item I want to check the contents of the edittext eg is the number larger than 10 if so change it to 10.
How should I do this.
set setOnFocusChangeListener
to your edittext...
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
}
If someone wants to do this in kotlin and with databinding then please refer below code
//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"
}
}
}
I had it explained in this post if you are interested.Go check it out https://medium.com/@mdayanc/how-to-use-on-focus-change-to-format-edit-text-on-android-studio-bf59edf66161
Here is the simple code to utilize 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
}
}
});