getActionView is deprecated?

2019-02-11 13:00发布

问题:

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 !

回答1:

The Javadoc says:

Use getActionView() directly.

Hence, what you should do is:

val searchView = searchItem.getActionView() as SearchView


回答2:

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;


回答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;
}


回答4:

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)
}