P Chan P Chan - 23 days ago 6
Android Question

SearchView not getting focus

EDIT For anyone wondering, my problem was I was using

android.widget.SearchView
instead of
android.support.v7.widget.SearchView
. I hope this helps anyone else with the same problem!

Original Post

I'm trying to implement SearchView in the Android ActionBar as per the official guide: http://developer.android.com/training/search/setup.html

After failing to find the problem, I finally stripped down to the most basic Hello World application and found to my surprise that the bug still persists in a minimal app!

Here's the bug:
The search icon appears in the menu bar, no problem. When I click it, the search bar expands (as expected) but there is no cursor and no soft keyboard appears. (I want to post a picture but my reputation is too low :(

Here is the relevant code, although I literally just created a new Android Application and added the item to menu/menu_main.xml.
MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}


menu_main.xml

<item android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="@android:string/search_go"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.widget.SearchView" />

Answer

use this is menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="your activity context here"><item
    android:id="@+id/mi_search"
    android:title="@string/search"
    android:orderInCategory="2"
    android:icon="@drawable/searchicon"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.support.v7.widget.SearchView" />

and this code in onCreateOptionsMenu(Menu menu):

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    MenuItem searchItem = menu.findItem(R.id.mi_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    searchView.setOnQueryTextListener(this);

    return super.onCreateOptionsMenu(menu);
}

in onOptionsItemSelected():

case R.id.mi_search:
    onSearchRequested();
    break;