9

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.

Somk
  • 11,869
  • 32
  • 97
  • 143
  • Maybe in this thread: http://stackoverflow.com/questions/4310525/android-on-edittext-changed-listener you have what are you want. – icastell May 16 '12 at 20:10

4 Answers4

13

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");
                }
            }
        });
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • Obviously late to the party, but using setText here will output the warning "getTextBeforeCursor on inactive InputConnection" – David Murdoch Nov 24 '15 at 20:41
3
 EditText ET =(EditText)findViewById(R.id.yourtextField);
ET.setOnFocusChangeListener(new OnFocusChangeListener() {
            public void onFocusChange(View arg0, boolean arg1) {

String myText = ET.getText();
//Do whatever

} 
Raheel
  • 4,953
  • 4
  • 34
  • 40
3

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"
       }
      }
     }
Rohan Sharma
  • 374
  • 4
  • 11
2

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
            }
        }
    });