1

When adding a SearchView to the menu (see example below), it's icon doesn't change and it behaves in a non-standard way. For example, long clicking on the search menu button should have popped the text Search, but it doesn't.

How do I change its behavior to be more standard? (icon and long click for now. I'm sure there are other issues)

Code sample for adding the view:

MenuItem item = menu.add("Search");
SearchView sv = new SearchView(getActivity());
item.setActionView(sv);
item.setIcon(drawable.menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

Thanks.

4

1 回答 1

6

更新:可以从代码中获得。您必须添加MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW和更改 to 的SearchView上下文getActionBar().getThemedContext()

MenuItem item = menu.add("Search");
SearchView sv = new SearchView(getActionBar().getThemedContext());
item.setActionView(sv);
item.setIcon(R.drawable.ic_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
        | MenuItem.SHOW_AS_ACTION_IF_ROOM);

您正在尝试SearchView从代码创建操作项,这不是建议的方法。定义一个包含搜索项的菜单资源,如下所示:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:actionViewClass="android.widget.SearchView"
        android:icon="@drawable/ic_search"
        android:showAsAction="collapseActionView|ifRoom"
        android:title="@string/search_title"/>

</menu>

充气onCreateOptionsMenu

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

这将解决问题。有关更多信息,请阅读Android 文档中的将搜索视图添加到操作栏

于 2013-05-05T11:50:44.790 回答