Arslan Aziz
Arslan Aziz

Reputation: 11

How to implement multiple backstacks using Navigation arch component android?

I want to implement a simple flow of fragments but with multiple back stacks using Navigation Component

I have a viewpager in my main activity with tabs at the bottom, pressing on the tabs or sliding on the viewpager slides to the next or previous fragment

What i have done so far is

1 - make multiple nav graphs, i thought thats how we will make multiple backstacks

nav-graph-1 nav-graph-2 ..

2 - in my viewpager i create fragments like this

 public Fragment getItem(int position) {
        if (position == 0)
            return NavHostFragment.create(R.navigation.navigation_all_news);
        else if (position == 1)
            return NavHostFragment.create(R.navigation.navigation_my_news);
        else if (position == 2)
            return NavHostFragment.create(R.navigation.navigation_search);
        else if (position == 3)
            return NavHostFragment.create(R.navigation.navigation_forum);
        else
            return NavHostFragment.create(R.navigation.navigation_settings);
    }

3 - i have handled backpresses in my fragments like this

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        navController = findNavController(this);

        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                navController.navigateUp();
                **//or navController.popBackStack()
                //Both have same effect :/**
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

    }

4 , if when i go

from viewpager first item (fragment1) to (fragment1.1) and press back, the (fragment1.1) pops

BUT

if i go

(fragment1) to (fragment1.1)
slide the viewpager (fragment2) to (fragment2.1)

or Vice Versa

now the backStack has 3 fragments (fragment2.1) and (fragment1.1) both included

am i doing something wrong or this just doesnt work with multiple nav graphs and Navigation arch?

Upvotes: 1

Views: 2980

Answers (1)

Kostek
Kostek

Reputation: 282

I don't want to discourage you from digging, but I am doing exactly the same for a quite some time now and it seems like there are only workarounds so far for complicated scenarios like multiple back stack.

Here is an example how people from Google has addressed this issue (still it is a workaround): https://github.com/android/architecture-components-samples/blob/master/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/NavigationExtensions.kt

I would go for a classic implementation until they get it working.

Nevertheless, good luck in your further researches!

Upvotes: 2

Related Questions