Search code examples
androidlistenersearchviewonfocusandroid-search

Android SearchView: What is the difference between setOnFocusChangeListener() and setOnQueryTextFocusChangeListener?


From the reference docs,

SearchView.setOnQueryTextFocusChangeListener - Sets a listener to inform when the focus of the query text field changes.

and

View.setOnFocusChangeListener - Register a callback to be invoked when focus of this view changed.

So, in the case of a SearchView what is the difference between the two? Why did they need to provide setOnQueryTextFocusChangeListener when the SearchView already inherits setOnFocusChangedListener from View class?


Solution

  • If you look inside the source code for SearchView then you'll notice that technically there's no difference in the working behavior of these two alternates. A part of code that proxies listeners is:

     // Inform any listener of focus changes
     mQueryTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
         public void onFocusChange(View v, boolean hasFocus) {
             if (mOnQueryTextFocusChangeListener != null) {
                 mOnQueryTextFocusChangeListener.onFocusChange(SearchView.this, hasFocus);
             }
         }
     });
    

    The reason is that SearchView is a ViewGroup which serves the purpose of querying text, and by making it more imminent, a separate method with very specific name is provided, which simply proxies to the existing setOnFocusChangeListener method of AutoCompleteTextView inside.