Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event for Handling the Focus of the EditText

People also ask

How do I know if EditText has focus?

You can use View. OnFocusChangeListener to detect if any view (edittext) gained or lost focus. This goes in your activity or fragment or wherever you have the EditTexts.

Which of the following method is used to set the EditText text?

In android, we can set the text of EditText control either while declaring it in Layout file or by using setText() method in Activity file.


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

When in Kotlin it will look like this:

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

  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.


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

            }
        }
    });