新设计中的Android switch Fragments支持导航抽屉 [英] Android switch Fragments in the new design support navigation drawer

查看:92
本文介绍了新设计中的Android switch Fragments支持导航抽屉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在新设计支持导航抽屉中切换片段"?我在Cheesesquare Github上找到了有关如何使用TabLayout而不是导航抽屉切换片段的示例代码.一样吗我也不想在切换时重新创建片段,而是像TabLayout那样保留片段实例,而片段的内容就是用户离开它的方式.

how can I switch Fragments in the new design support navigation drawer? I found example codes on the Cheesesquare Github on how to switch fragments using the TabLayout, but not the navigation drawer. Is that the same? I also would not like to recreate fragments when switching, but rather do it like the TabLayout where it retains the fragments instance and the fragment`s content is how the user left it.

推荐答案

编写如下代码:

navigationView.setNavigationItemSelectedListener(
        new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        menuItem.setChecked(true);
        mDrawerLayout.closeDrawers();
        switch (menuItem.getItemId()) {
            case R.id.your_menu_id: 
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment, getFragment(), "SET_A_TAG").addToBackStack("SET_A_TAG").commit();
                break;
        }
        return true;
    }
});

private YourFragment getFragment() {
    YourFragment f = getSupportFragmentManager().findFragmentByTag("SET_A_TAG");
    if (f == null) {
        f = new YourFragment();
    }
    return f;
}

这篇关于新设计中的Android switch Fragments支持导航抽屉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆