简体   繁体   中英

How can go to the previous fragment in backstack?

I have a MainActivity in the onCreate method i add a fragment like this :

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, new FragmentA(), FRAGMENT_TAG).addToBackStack("main")
                .commit();

In FragmentA there is a lisview and when user clicked on an item i remove FragmentA and add FragmentB (In FragmentA there is a FragmentPagerAdapter and in FragmentPagerAdapter is a ListFragment in ListFragment i called below code )

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_frame, new FragmentB(), MainActivity.FRAGMENT_TAG).addToBackStack("main")
                        .commit();
};

Now in FragmentB there is button and whenever user clicked on it i want to go back to the FragmentA . I try to call popBackStack() in button listener but nothing happen

 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 fragmentManager.popBackStack();

Or i also try this below code but it gives me nullpointer exception

   FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
        Fragment currentFragment =getActivity().getSupportFragmentManager()
                .findFragmentByTag(fragmentTag);
        fragmentManager.beginTransaction().replace(R.id.content_frame,currentFragment).commit();
        fragmentManager.popBackStack();

如果要转到BackStack的上一个Fragment ,则只需执行onBackPressed()

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