user2422723
user2422723

Reputation: 1

Is it possible to replace the current viewed fragment in FragmentStatePagerAdapter without swiping to other pages first?

I have succeeded replacing fragments in a FragmentStatePagerAdapter but it requires swiping out of the fragment in order for it to be destroyed and re-create a different fragment, thus replacing the fragment.

What I need is to replace the current viewed fragment of the adapter with another fragment without changing the current viewed fragment.

Example:

Page1 Page2 Page3 Page4

Page4 is the active fragment. When I clicked something in Page4, it will be replaced by another fragment

Page1 Page2 Page3 Page3

fragmentDataSource[3] = page3Fragment;
adapter.notifyDataSetChanged();

Only works because of the onChange() method. (Wild guess)

Is this possible? I have considered using FrameLayout and just set the visibility of the layouts, but I don't think it will be the best choice.

Thanks!

Upvotes: 0

Views: 204

Answers (1)

Mikelis Kaneps
Mikelis Kaneps

Reputation: 4584

This is not the most efficient way how to re-instantiate the Fragment in ViewPager but it is the simplest:

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

Or make a method in the Fragment and call it, if the fragment has the correct tag:

@Override
        public Fragment getItem(int position) {         
            if (position == some position) {
                YourFragment myFragment = YourFragment.newInstance(someObject);
                myFragment.setmTag("some tag");
                return myFragment;
            }
            //some code

}

@Override
        public int getItemPosition(Object object) {
            YourFragment frag = ((YourFragment) object);
            if (frag.getmTag()!="some tag") {
                ((YourFragment) object).update(someObject);

            }

            return super.getItemPosition(object);
        } 

Upvotes: 0

Related Questions