2

I've got a collections of fragment as : [Fragment1][Fragment2][Fragment3]

I'm using ViewPager and FragmentPagerAdapter. What I'm trying to do is to replace Fragment2 to another fragment (let's call it Fragment4), when a view inside Fragment2 is clicked. I'm using the code as below :

newMsgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swapFragment(new Fragment4());
            }
        });
    private void swapFragment(Fragment fragment){
        FragmentTransaction fragmentTransaction = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.view_container,fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

Then when I clicked on the newMsgBtn, it detect the click but it's unable to change the fragment. Any idea how to do this ? thanks

VincentTheonardo
  • 329
  • 1
  • 6
  • 18

3 Answers3

1

In addition to Kingfisher Phuocr answer, you can change the fragment in this method

@Override
public void onBackPressed() {
    ArrayList myList = FragmentStatePagerAdapter.customFragmentsArrayList.remove(position);
    myList.add(position,new Fragment_Number());   //i.e. your fragment number
    viewPagerAdapter.notifyDataSetChanged();
}
Daksh Gargas
  • 3,498
  • 2
  • 23
  • 37
0

I think this should be done in your FragmentStatePagerAdapter. You should do something like:

new FragmentStatePagerAdapter(fm) {
public int getCount() {
    return fragments.size(); // the fragments list
}

public Fragment getItem(int position) {
    return fragments.get(position);
}

public int getItemPosition(Object item) {
        return POSITION_NONE;
}
}

Every time you want to change your viewpager fragment, you can call:

fragments.remove(1); //remove your fragment 2
fragments.add(1,fragment4); // add your fragment4 into the 2 position
viewPagerAdapter.notifyDataSetChanged();
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
0

Here's the fix :

private void changeFragment(Fragment fragment) {
    MainActivity activity = (MainActivity) getActivity();
    activity.adapter.fragmentList.remove(0);
    activity.adapter.fragmentTitleList.remove(0);
    activity.adapter.fragmentList.add(0,fragment);
    activity.adapter.fragmentTitleList.add(0,fragment.getClass().getSimpleName());
    activity.pager.getAdapter().notifyDataSetChanged();
}

Make sure you adapter object and pager (ViewPager) instance are public.

Daksh Gargas
  • 3,498
  • 2
  • 23
  • 37