我有FoodListFragment
和FoodDetailFragment
。
在FoodListFragment
我在SearchView
中设置topBar
,并为querytextChange
提供了监听:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
this.getActivity().getMenuInflater().inflate(R.menu.main, menu);
//Associate searchable configuration with the SearchView
searchManager = (SearchManager) this.getActivity().getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.search);
searchView = (SearchView) searchItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getActivity().getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String textToFind) {
// your text view here
if (foodAdapter == null) {
foodAdapter = ((FoodListFragment) getFragmentManager().findFragmentByTag(Const.FOODLIST_FRAGMENT)).getFoodAdapter();
}
foodAdapter.getFilter().filter(textToFind.toString());
return true;
}
@Override
public boolean onQueryTextSubmit(String textToFind) {
Log.d("submit by search", TAG);
if (foodAdapter == null) {
foodAdapter = ((FoodListFragment) getFragmentManager().findFragmentByTag(Const.FOODLIST_FRAGMENT)).getFoodAdapter();
}
foodAdapter.getFilter().filter(textToFind.toString());
searchView.clearFocus();
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
当我使用show并隐藏时,从FoodListFragment
转换为FoodDetailFragment
:
public void switchContent(int id, Fragment fragment, String tagFrag) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if(fragment.isAdded()){
transaction.show(fragment);
} else {
transaction.add(id, fragment, tagFrag);
}
transaction.addToBackStack(null);
if(Const.FOODDETAIL_FRAGMENT.equals(tagFrag)){
if(getFragmentManager().findFragmentByTag(Const.FOODLIST_FRAGMENT) != null){
FoodListFragment foodListFrag = (FoodListFragment) getFragmentManager().findFragmentByTag(Const.FOODLIST_FRAGMENT);
transaction.hide(foodListFrag);
}
}
// Commit the transaction
transaction.commit();
}
调用onQueryTextChange
的{{1}}方法,searchView
为空,因此当我回到textToFind
时,FoodListFragment
不会保留上次搜索。
为什么在隐藏片段期间调用searchView
?
为什么textToFind是空的?