我有MainActivity,它持有2个片段。第一个片段有导航抽屉,第二个片段没有。在MainActivity中,我想覆盖onBackPressed()方法,因此当打开导航抽屉时,它必须关闭片段。但我不知道如何从Activity中获取片段的导航抽屉状态。这是代码:
MainActivity.java
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
FragmentListProduct.java
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.fragment_list_product_layout, container, false);
Toolbar toolbar = (Toolbar) mainView.findViewById(R.id.toolbar);
fragmentActivity.setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) mainView.findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(fragmentActivity, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
navigationView = (NavigationView) mainView.findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_cat_all);
}
当然它给了我错误Cannot resolve symbol darwerlayout
。
在我将drawerLayout
作为静态字段之前,我收到了警告Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
。那么如何解决这个问题,或者你有另一个解决方案:D
答案 0 :(得分:1)
您可以使用标签访问该片段,您在调用片段时必须分配该片段,如下所示:
getFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment, "the_tag_here")
.commit();
使用getFragmentManager().findFragmentByTag("the_tag")
@Override
public void onBackPressed() {
FragmentListProduct fragment = (FragmentListProduct) getFragmentManager().findFragmentByTag("the_tag_here");
if (fragment != null) {
DrawerLayout drawerLayout = fragment.drawerLayout;
//make drawerLayout public in the fragment
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
答案 1 :(得分:0)
解决方案1:
解决方案2:
在此活动中获取片段参考
Fragment yourFragment = (YourFragment)getSupportFragmentManager().findFragmentById(R.id.containerId);
在你的onBackPressed()中调用yourFragment.checkNavigationDrawer();像这样
@Override
public void onBackPressed() {
yourFragment.checkNavigationDrawer();
super.onBackPressed();
}
在checkNavigationDrawer方法中,检查导航抽屉是否打开,如果它是打开的,请关闭它。
public void checkNavigationDrawer(){
if(drawerLayout.isOpen()){
drawerLayout.closeDrawers();
}
}