Getting a SearchView with MenuItemCompat (Android)

2020-07-10 08:36发布

问题:

I am trying to implement the SearchView ActionBar item as android developers says but I am having some trouble. (http://developer.android.com/guide/topics/ui/actionbar.html).

There are two mistakes that although I have looked for a lot, I have not been able to find the solution.

1) I have a problem with the class MenuItemCompat. It says: The method getActionView(MenuItem) is undefined for the type MenuItemCompat

I can only use for this class the following methods:

  • setShowAsAction(item, actionEnum)
  • setActionView(item, view)

Here it is the code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.restloader, menu);
    MenuItem searchItem = menu.findItem(R.id.search_menu);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);       

    // Configure the search info and add any event listeners

    return super.onCreateOptionsMenu(menu);
}

2) There is a problem with this: xmlns:myapp="http://schemas.android.com/apk/res-auto" I don't understand why it is used but if google says it, it must be appropriate.

Error message: Multiple annotations found at this line: - error: No resource identifier found for attribute 'actionViewClass' in package 'com.example.pruebahttp3' - error: No resource identifier found for attribute 'showAsAction' in package 'com.example.pruebahttp3'

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/search_menu"
    android:orderInCategory="100"
    android:title="@string/search"
    android:icon="@drawable/ic_search_category_default"
    myapp:showAsAction="ifRoom|collapseActionView"
    myapp:actionViewClass="android.support.v7.widget.SearchView">         
</item>

Thank you very much!

回答1:

i have got the same problem, i solved it by using the follow code. Be care of your namespace.`

<!-- Search, should appear as action button -->
<item
    android:id="@+id/action_search"
    android:icon="@drawable/abc_ic_search"
    share:showAsAction="ifRoom"
    share:actionViewClass="android.support.v7.widget.SearchView"
    android:title="@string/abc_searchview_description_search" />

`



回答2:

For the 1st:Fixing the second one will fix this :)

For the 2nd:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto" >

Change myapp to you application namespace com.xxx.xxx



回答3:

Try to copy the lib files directly from yourFolder\sdk\extras\android\support\v7\appcompat\libs I have a similar problem,but It occurs to me when i directly copy the JAR library file rather than following the android support library procedure. Try the opposite it might work for you. Kinda weird if you ask me.