简体   繁体   中英

Navigation Drawer with nested fragments (ViewPager)

I am writing an app which has a Navigation Drawer and is using nested fragments. The navigation drawer is created pretty much as per Android docs - it works. I want the navigation drawer to be visible always, that's why I have one activity with it, and I just swap fragments. One of the fragments is a ViewPager , which in turn has its own fragments as pages.

The navigation is hierarchical like this:

- Home
- Fragment 1
-- Subfragment 1.1
-- Subfragment 1.2
-- Subfragment 1.3
- Fragment 2
-- Subfragment 2.1
-- Subfragment 2.2
-- Subfragment 2.3

where Fragment is a ViewPager , and Subfragments are its pages. All works correctly when I just go to Fragment from the drawer, but I don't know how to switch directly to a ViewPager's given page (nested fragment) .

MainActivity with handling nav drawer clicks:

@Override
protected void onNavItemSelected(int id) {
    switch ((int)id) {
        case 1:
            getSupportFragmentManager().beginTransaction()
            .replace(R.id.content_frame, new MainFragment())
            .addToBackStack(null).commit(); 
            break;
        case 100:
            getSupportFragmentManager().beginTransaction()
            .replace(R.id.content_frame, new Fragment1())
            .addToBackStack(null).commit();
            break;
        case 200:
            getSupportFragmentManager().beginTransaction()
            .replace(R.id.content_frame, new Fragment2())
            .addToBackStack(null).commit();
            break;
        .
        .
        .
    }    
}

I suppose this should be something with getChildFragmentManager() and ViewPager's setCurrentItem() , but I can't get the first in my Main Activity (or don't know how) and I can't use the second because the pager is not created yet if I do something like this:

SubFragment11 a = new SubFragment11();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, a).addToBackStack(null).commit();
a.setCurrentPagerItem(2);

Provide the ViewPager fragment with a Bundle with a variable to control the selected item. When the Viewpager is created, get that integer and switch to that panel.

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