Event for Handling the Focus of the EditText

Can anyone suggest to me any event related to the focus of the EditText? My application contains an EditText, which accepts a URL in it.

Now my problem is that, that after the user will enter the URL in the field and Move further, without any of the click events, i.e when the focus will move from the EditText, it should detect the entered Url and goes to the server.

If I get the reply using Json Parsing, then it'll be more convenient.


Solution 1:

Here is the focus listener example.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
        }
    }
});

Solution 2:

When in Kotlin it will look like this:

editText.setOnFocusChangeListener { _, hasFocus ->
    if (hasFocus) {
        toast("focused")
    } else {
        toast("focuse lose")
    }
}

Solution 3:

  1. Declare object of EditText on top of class:

    EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                 @Override
                 public void onFocusChange(View view, boolean hasFocus) {
                     if (!hasFocus) {
                          Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                     }else{
                         Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                     }
    
                 }
             });
    

It works fine.

Solution 4:

For those of us who this above valid solution didnt work, there's another workaround here

 searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean isFocused) {
            if(!isFocused)
            {
                Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();

            }
        }
    });