从活动

时间:2016-12-05 09:33:38

标签: java android android-fragments

我有一个包含片段的活动,然后在片段中我有包含SearchView的工具栏。我想覆盖活动的onBackPressed()来关闭searchView的焦点。但我还没有找到如何获得片段菜单的状态。这是代码:

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);
}

那么如何在活动中获取片段的菜单以便我可以访问其状态?

1 个答案:

答案 0 :(得分:0)

您可以通过片段公开onCreateOptionsMenu()中的视图,并使用isIconified()来检查状态,使用setIconified(true)来关闭它。

<强> 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
       }
    }

/...
}