错误在ActionBar中的SearchView
我有一个搜索视图的操作栏,我有一个片段设置选项菜单。 在我的MainActivity SearchView工作正常,但在我的片段(我需要处理事件OptionMenuItem做些事情),setHasOptionMenu后,然后SearchView无法正常工作。 这是我的代码
MainActivity中的选项菜单
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); // Create SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setSubmitButtonEnabled(false); searchView.setQueryHint("Search Here"); searchView.setSearchableInfo(searchManager .getSearchableInfo(getComponentName())); SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { if(s.length() > 0){ Tab1.listadaptor.getFilter().filter(s); Tab2.listadaptor.getFilter().filter(s); }else{ pager.setAdapter(adapter); if(SlidingTabLayout.userState){ pager.setCurrentItem(0); }else{ pager.setCurrentItem(1); } } return true; } }; searchView.setOnQueryTextListener(queryTextListener); return super.onCreateOptionsMenu(menu); }
OptionMenuItem在片段中
@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ //Do Something } return super.onOptionsItemSelected(item); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); }
这工作! 在Kotlin,如果你需要更多的帮助,请告诉我。
override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) val inflater = menuInflater inflater.inflate(R.menu.search_activity_menu, menu) searchView = menu.findItem(R.id.btn_search_station).actionView as SearchView return true } private fun setErrorOnSearchView(searchView: SearchView, errorMessage: String) { val id = searchView.context .resources .getIdentifier("android:id/search_src_text", null, null) val editText = searchView.find(id) editText.error = errorMessage } private fun cleanErrorOnSearchView(searchView: SearchView) { val id = searchView.context .resources .getIdentifier("android:id/search_src_text", null, null) val editText = searchView.find (id) editText.error = null }