Search code examples
androidandroid-layoutandroid-actionbarsearchviewactionview

How to add SearchView to action bar in android


In the following snippet, what does yourapp refer to? I try using the package name, then the project name, but they aren't the answer as the code does not compile

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/action_search"
          android:title="@string/action_search"
          android:icon="@drawable/ic_action_search"
          yourapp:showAsAction="ifRoom|collapseActionView"
          yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

Solution

  • if you are going to use SearchView in API less than 11 (obviously you are not) you must extend your activity from ActionBarCompatand in your xml layout of your menu you must use another xml name space for showAsAction and actionViewClass. then you must use searchview from support library.(android.support.v7.widget.SearchView) the xml name space is arbitary and here you called it yourapp. So you must use below code because of android:minSdkVersion="11":

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
           >
        <item android:id="@+id/action_search"
              android:title="@string/action_search"
              android:icon="@drawable/ic_action_search"
              android:showAsAction="ifRoom|collapseActionView"
              android:actionViewClass="android.widget.SearchView" />
    </menu>