34

Today I decide to translate my android app from Java to Kotlin ! :) But I was very surprise when I type this :

val searchItem = menu.findItem(R.id.action_search)
val searchView = MenuItemCompat.getActionView(searchItem) as SearchView

And Android Studio told me : " 'getActionView(MenuItem!):View!' is deprecated. Deprecated in Java "

So before to ask you the solution I ask to Google what is the solution and I believed I find the solution : "Use getActionView() directly."

So I modified my code like this :

val searchView = MenuItemCompat.getActionView() as SearchView

But getActionView() is still crossed so I don't understand at all...

I will be very happy if you can help me :) Thank you !

K.Os
  • 5,123
  • 8
  • 40
  • 95
Ross Thomas
  • 343
  • 1
  • 3
  • 4

4 Answers4

63

The Javadoc says:

Use getActionView() directly.

Hence, what you should do is:

val searchView = searchItem.getActionView() as SearchView
Egor
  • 39,695
  • 10
  • 113
  • 130
  • Just to add to this, the [docs](https://developer.android.com/reference/android/support/v4/view/MenuItemCompat.html#getActionView(android.view.MenuItem)) actually link the `getActionView` method of `MenuItem` in the deprecation info. – zsmb13 Jul 25 '17 at 15:45
13

As suggested by egor, you can do like this

    getMenuInflater().inflate(R.menu.menu_items, menu);
    MenuItem menuItem = menu.findItem(R.id.action_search);

    SearchView searchView = (SearchView) menuItem.getActionView();
    search(searchView);
    return true;
Ashish Kumar
  • 131
  • 1
  • 2
3

You can use the same as provided on android developer website

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the options menu from XML
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    // Get the SearchView and set the searchable configuration
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    // Assumes current activity is the searchable activity
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

    return true;
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Ramapati Maurya
  • 654
  • 9
  • 11
0

Use actionView directly in Kotlin, like this:

  override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.actions, menu)
    val searchItem = menu?.findItem(R.id.action_search)
    val searchView = searchItem?.actionView as SearchView
    searchView.animate()
    // TODO: Configure the search info and add any event listeners...
    return super.onCreateOptionsMenu(menu)
}
Harry Zhang
  • 799
  • 9
  • 6