Skip to content Skip to sidebar Skip to footer

Searchview.isfocused Always Returns False

I'm trying to determine whether a SearchView in the ActionBar is focused. But when I call SearchView.isFocused() I always get false as a result, even when the view is really focuse

Solution 1:

After some researching, I learned that SearchView.isFocused() always returns false because it's some child of the SearchView who really has the focus, not the SearchView itself. So I use the following code to check the focus of a SearchView:

privatebooleancheckFocusRec(View view) {
    if (view.isFocused())
        returntrue;

    if (view instanceof ViewGroup) {
        ViewGroupviewGroup= (ViewGroup) view;
        for (inti=0; i < viewGroup.getChildCount(); i++) {
            if (checkFocusRec(viewGroup.getChildAt(i)))
                returntrue;
        }
    }
    returnfalse;
}

So I call checkFocusRec(searchView) to check for the focus. I'm not sure this is the optimal solution but it works for me.

Solution 2:

Looks like an ugly (or bug) implementation from SearchView. My suggestion is to extend the SearchView and create methods like so:

var isQueryFocused = falseprivateset// you can also override hasFocus() and isFocused() methods, if you preferfunhasQueryFocus() = isQueryFocused

overridefunsetOnQueryTextFocusChangeListener(listener: OnFocusChangeListener?) {
    super.setOnQueryTextFocusChangeListener { v, hasFocus ->
        isQueryFocused = hasFocus
        listener?.onFocusChange(v, hasFocus)
    }
}

The other answers use recursive calls which is not a very efficient and private resource ID (the inner TextView id) which is a bad practice.

Solution 3:

When looking at this question and its solution, I found some extra information in the resource files included with the Android SDK (in the folder sdk/platforms/android-xx/data/res/layout/search_view.xml).

The subview holding focus has id @+id/search_src_text and is of type android.widget.SearchView$SearchAutoComplete.

I would therefore suggest the following alternative to the previous solution:

privatebooleanisSearchViewFocused(SearchView sview) {
    Viewet_search=  sview.findViewById(R.id.search_src_text);
    return et_search.isFocused();
}

Post a Comment for "Searchview.isfocused Always Returns False"