Ok here's my problem, I have three fragments, let's call them [1], [2] and [3].

Here's the path I want the them to follow:

[1] > [2] > [3] >(back-key)> [1]

For some reason, this only works once, when I try to go for round 2, here's what happens:

[1] > [2] > [3] >(back-key)> [1] > [2] > [3] >(back-key)> [3] >(back-key)> Exit

That is to say, when I get to [3] for the second time and press the back button, nothing happens, If I press again my app exits to android. (never returns to [1])

I'm pretty sure this has something to do with the method addToBackSack, but I can't quite put my finger on it.

Here's my code

[A]

    public void onClick(View v) {

        Fragment fragment = new [B]Fragment();
        FragmentManager fm = this.getActivity().getFragmentManager();

        FragmentTransaction transaction = fm.beginTransaction();


        transaction.replace(R.id.container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    }

[B]

    public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {

    Fragment fragment = new [C]Fragment();
    FragmentManager fm = this.getActivity().getFragmentManager();

    FragmentTransaction transaction = fm.beginTransaction();

    transaction.replace(R.id.container, fragment);

    transaction.commit();

}

I'm not using addToBackStack on [B] because I don't want android to remember this transaction, am I right?

Thanks!

有帮助吗?

解决方案

Ok! found the answer!.

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Toast.makeText(this.getActivity(), "New order created",
            Toast.LENGTH_SHORT).show();
    Fragment fragment = new OrderFragment();
    FragmentManager fm = this.getActivity().getFragmentManager();
    fm.popBackStack();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.addToBackStack(null);
    transaction.replace(R.id.container, fragment);
    transaction.commit();

}

The function popBackStack() did the trick! :) I'm not sure how this works yet. But it does!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top