android – 在Fragment中添加SearchView
作者:互联网
尝试在操作栏中包含搜索查看.为此,我做了以下事情:
在菜单文件夹中创建了MenuSearch.xml,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_search"
android:actionViewClass="Android.Support.V7.Widget.SearchView"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="always"
android:title="Search"/>
</menu>
包含片段中的OnCreateOptionsMenu方法:
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
inflater.Inflate(Resource.Menu.MenuSearch, menu);
base.OnCreateOptionsMenu(menu, inflater);
var searchManager = (SearchManager) this.Activity.GetSystemService(Context.SearchService);
searchView = (SearchView) (menu.FindItem(Resource.Id.action_search).ActionView);
searchView.SetSearchableInfo(searchManager.GetSearchableInfo(Activity.ComponentName));
}
我设置了HasOptionsMenu = true;在片段的oncreate.
使用上面的代码,我在searchView.SetSearchableInfo …行中获得空指针.不知道为什么会发生这种情况,尽管一切似乎都是正确的.
基于解决类似问题的一些建议,我还尝试了searchview的以下选项.
var item = menu.FindItem (Resource.Id.action_search);
var searchItem = MenuItemCompat.GetActionView(item);
searchView = searchItem.JavaCast<Android.Support.V7.Widget.SearchView>();
searchView.SetSearchableInfo(searchManager.GetSearchableInfo(Activity.ComponentName));
但同样,我将searchView视为null.
现在我已经尝试了可能的选项,我对于为什么searchview变为null无能为力.
任何帮助深表感谢.
解决方法:
将MenuSearch.xml更改为
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search"
android:title="@string/app_name"
android:icon="@drawable/ic_action_search"
app:showAsAction="collapseActionView|ifRoom"
/>
</menu>
并在您的片段中添加searchView.setOnQueryTextListener
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_option_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = new SearchView(((MainActivity) mContext).getSupportActionBar().getThemedContext());
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
}
);
}
标签:android,xamarin,searchview 来源: https://codeday.me/bug/20191004/1853073.html