SearchView returning as ViewGroupInvoker RRS feed

  • Question

  • User71316 posted


    I'm developing an Android application targeting API 21, but using the AppCompat libraries so I can have the same Material look and feel on API 19 devices as well. I have an ActionBarActivity that uses a Toolbar object as its ActionBar. I am running into an issue where I am unable to acquire a handle to the SearchView action view in the menu. The relevant code is below:

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


        using SearchView = Android.Support.V7.Widget.SearchView;
        public override bool OnCreateOptionsMenu(IMenu menu)
            MenuInflater inflater = this.MenuInflater;
            inflater.Inflate(Resource.Menu.menu, menu);
            IMenuItem searchItem = menu.FindItem(Resource.Id.search_view);
            var searchView = searchItem.ActionView as SearchView;
            return true;

    The code above will fail because the ActionView is not able to be typed to SearchView at runtime. If I remove the cast to SearchView, the type is ViewGroupInvoker. This should not be happening according to all the examples I see online. Since the documentation is kind of lacking for this, I thought I would ask here.

    Tuesday, February 17, 2015 6:35 PM

All replies

  • User209 posted

    When using the Support packages you will need to do this instead to find the ActionView:

    var searchView = MenuItemCompat.GetActionView(item);
    var actualSearchView = searchView.JavaCast<SearchView>();

    See more here: https://gist.github.com/Cheesebaron/9838325

    Tuesday, February 17, 2015 9:47 PM
  • User71316 posted

    Thank you!

    This is the first instance of me seeing the JavaCast method used. I'd like to understand more why it's required here specifically. Could you point me towards any documentation?

    Wednesday, February 18, 2015 12:22 AM
  • User209 posted

    Docs here

    Note: This is a hack, but a currently necessary one. Most of the Android types are staticly generated wrappers over a description of the underlying Android types. This intermediate description does not expose implementation details, which sometimes must be relied upon.

    I think @JonathanPryor had a nice answer to that somewhere on the forums

    It might be OK to just cast it in this case, you can try it for yourself. I just do it to be safe :smile:

    Wednesday, February 18, 2015 9:36 AM