Search code examples
androidandroid-fragmentsandroid-viewpager

How to Reload the fragment from another fragment inside the viewpager in android


now iam having a view pager inside the activity. ViewPager have two fragments. Now i want to reload the fragment while swiping or it gets moved from one fragment to another by using objViewPager.setcurrentitem(0) or objViewPager.setcurrentitem(0). Please help... what i want is i want to refresh the second or first fragment while moved from first to second or second to first fragment respectively.. I have gone through many searches but all told fragment communication alone but not inside the view pager.....please suggest me ideas .


Solution

  • From what i can understand from the question you want to make changes in the fragments when the user swipes right ? Basically you can just make an interface in the activity and implement it in the fragments.Call this interface in the ViewPager.setOnPageChangeListener.(Where the above answer suggested).

    Something like this . In the Activity,

    public interface FragmentInterface{
        void Fragmentbecamevisible();
    }
    

    and call the function in the ViewPager.setOnPageChangeListener

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
    
        }
    
        @Override
        public void onPageSelected(int i) {
            //do the setselectednavigationitem
            FragmentInterface frag=(FragmentInterface)mAdapter.instantiateItem(viewPager, arg0);
                if(frag!=null)
                {
                    frag.Fragmentbecamevisible();
                }
    
        }
    
        @Override
        public void onPageScrollStateChanged(int i) {
    
        }
    });
    

    So the interface function is called each time the fragments are switched or whenever swipe function occurs. In the fragments just implement the interface , and in the Fragmentbecamevisible() function ,make all the changes you want to refresh the fragment.

    public class Statistics_Fragment extends Fragment implements FragmentInterface
    {   
    @Override
    public void Fragmentbecamevisible() {
        // TODO Auto-generated method stub
        //Make changes to your fragment.Each time the user navigates to this fragment .thhis function gets called
    
    
    }
    

    Hope this helps . Feel free to make changes.