Event for Handling the Focus of the EditText

AndroidEventsNetworking

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

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 - Android

When in Kotlin it will look like this:

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

Solution 3 - Android

  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 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSheetal ShelarView Question on Stackoverflow
Solution 1 - AndroidPratikView Answer on Stackoverflow
Solution 2 - AndroidarjavaView Answer on Stackoverflow
Solution 3 - AndroidWajid khanView Answer on Stackoverflow
Solution 4 - AndroidDev_ManView Answer on Stackoverflow