Communication objects between multiple fragments in ViewPager

前端 未结 7 1305
不知归路
不知归路 2021-02-07 06:53

I have 5 fragments in ViewPager used to fill business object with several fields step by step, in each step some of those fields will be set. I\'ve read many articl

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 07:27

    I suppose in your MainActivity there is a ViewPager, and FragmentOne will be one of the fragments inside the view pager. Here the MainActivity is communicating to the FragmentOne to refreshhis adapter. Hope is clear.

    In your MainActivity add this interface:

    public interface Updateable {
        public void update();
    }
    

    Implement this interface in a fragment that needs to be updated, and write the code to notify the adapter inside the update method:

    public class FragmentOne extends Fragment implements MainActivity.Updateable {
        ...
        @Override
        public void update() {
            // YOUR CODE TO UPDATE HERE, FOR EXAMPLE, HERE I'M UPDATING THE ADAPTER
            if ( adapter != null ) {
                adapter.notifyDataSetChanged();
            } else {
                Log.d("LOG_TAG", "null");
            }
        }
        ...
    }
    

    Call the update method from the MainActivity when the fragment loads first. You can do this overriding the getItemPosition method in your PagerAdapter, like this:

    @Override
    public int getItemPosition(Object object) {    
        if ( object != null && object instanceof FragmentOne ) {
            FragmentOne f = (FragmentOne) object;
    
            f.update();
        }
        return super.getItemPosition(object);
    }
    

    Finally, you have to call notifyDataSetChanged() of your viewPager adapter. This will force the adapter of your viewpager to call the getItemPosition method.

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            int previousState;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
            }
    
            @Override
            public void onPageSelected(int position) {
    
            }
    
            @Override
            public void onPageScrollStateChanged(int state) {
    
                if (previousState == ViewPager.SCROLL_STATE_SETTLING && state == ViewPager.SCROLL_STATE_IDLE) {
    
                    if ( viewPagerAdapter.getItem(viewpager.getCurrentItem()) instanceof Pictures ) {
                        Log.d("LOG_TAG", "New Position=" + viewpager.getCurrentItem());
    
                        viewPagerAdapter.notifyDataSetChanged();
                    }
    
                }
                previousState = state;
            }
        });
    

提交回复
热议问题