简体   繁体   中英

Get Fragment's SearchView's state from activity

I have an activity which is containing fragment, then in the fragment i have toolbar which is containing SearchView. I want to override activity's onBackPressed() to close the searchView's focus. But i didn't found how to get the state of fragment's menu. Here's the code :

MainActivity.java

@Override
public void onBackPressed() {
    if (currentFragment instanceof FragmentListProduct) {
        DrawerLayout drawerLayout = (DrawerLayout) currentFragment.getView().findViewById(R.id.drawer_layout);
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } /*if currentFragment.searchViewIsNotClosed {
            closeSearchView();
        } */ else if (backstackFragment.size() > 0) {
            replaceFragment(null, backstackFragment.pop());
        } else {
            super.onBackPressed();
        }
    } else {
        super.onBackPressed();
    }
}

FragmentListProduct.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.app_bar_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {...});

    super.onCreateOptionsMenu(menu, inflater);
}

So how to get fragment's menu in activity so i can access its state?

You can expose the view from the onCreateOptionsMenu() via the fragment and use isIconified() to check the status and setIconified (true) to close it.

FragmentListProduct.java

private SearchView searchView;
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //...
    searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    //...
}
public SearchView getSearchView() {
    return searchView;
}

MainActivity.java

public void onBackPressed() {
    //...
    SearchView searchView = ((FragmentListProduct)currentFragment).getSearchView();
    if (searchView != null) {
       if (searchView.isIconified()) {
         // the search is extended
         searchView.setIconified(true);
       } else {
         // the search view is closed
       }
    }

/...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM