FragmentPagerAdapter to onbackpressed

时间:2018-03-13 05:59:29

标签: android android-studio fragmentpageradapter

我有一个活动和四个片段。问题是,当我从任何片段开始一个活动时,导航会在此之后返回第一个片段。此外,当我导致onactivityforresult后,导航返回到第一个片段。 MainActivity Code是:

mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        private final Fragment[] mFragments = new Fragment[]{
                new RecentPostsFragment(),
                new DonorsFragment(),
                new PlaceActivity(),
                new MyTopPostsFragment(),

        };
        private final String[] mFragmentNames = new String[]{
                getString(R.string.heading_recent),
                getString(R.string.heading_donors),
                getString(R.string.heading_nearby),
                getString(R.string.heading_my_top_posts)
        };

        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }

        @Override
        public int getCount() {
            return mFragments.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentNames[position];
        }
    };
    // Set up the ViewPager with the sections adapter.
    mViewPager = findViewById(R.id.container);
    mViewPager.setAdapter(mPagerAdapter);
    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

片段代码是:

       @Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
                          Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
   // [START create_database_reference]
    mDatabase = FirebaseDatabase.getInstance().getReference();
    // [END create_database_reference]

    mRecycler = rootView.findViewById(R.id.messages_list);
    mRecycler.setHasFixedSize(true);

    return rootView;
}

1 个答案:

答案 0 :(得分:0)

试试这个: -

private void wannaReplaceFragment (Fragment fragment){
  String backState = fragment.getClass().getName();

  FragmentManager fm = getSupportFragmentManager();
  boolean fragmentPopped = fm.popBackStackImmediate (backState, 0);

  if (!fragmentPopped){
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backState);
    ft.commit();
  }
}

更换片段时,请使用popBackStackImmediate()方法。一旦您可以从此链接获取指南: - How to resume Fragment from BackStack if exists