在Fragment hide上,SearchView查询文本为空

时间:2016-10-13 09:20:14

标签: android android-fragments show-hide searchview

我有FoodListFragmentFoodDetailFragment。 在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是空的?

0 个答案:

没有答案