Vishwanath.M
Vishwanath.M

Reputation: 6317

ViewPager Refresh/Change Only Current Page/Fragment

Am having viewpager with 3 fragments/page, I have to refersh only current page or fragment, am calling mPagerAdapter.notifyDataSetChanged(), but its refreshing all pages,How to refresh or change only current page without refreshing or changing other pages

Upvotes: 1

Views: 8505

Answers (4)

Swapnil Lanjewar
Swapnil Lanjewar

Reputation: 686

Try this:

first of all you need to use a PagerAdapter which will be extending FragmentPagerAdapter in your MainActivity then in your getItem() method of the adapter use switch case for calling fragments like

public Fragment getItem(int pos) {
switch (pos) {

            case 0:
                return FirstFragment.newInstance("FirstFragment, instance 1");
            case 1:
                return SecondFragment.newInstance("SecondFragment, instance 1");
            case 2:
                return ThirdFragment.newInstance("ThirdFragment, instance 1");

            default:
                return FirstFragment.newInstance("");
        }
}

then set adapter in onCreate() of the activity like:

ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(new YourPagerAdapter(getSupportFragmentManager()));

Then use the following methods in every fragment you have:

public static FirstFragment newInstance(String text) {

    FirstFragment f = new FirstFragment();
    return f;
}

And

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser) {

        if (isNetworkAvailable()) {
            makeRequest();// do network calling and populate your views from here
        } else {
            Toast.makeText(getActivity(), "You are not connected\nto the internet!", Toast.LENGTH_SHORT).show();
        }

    }
}

I have also faced the same problem but solved it using this solution. I hope this will help you too.

Upvotes: 0

Jay Rathod
Jay Rathod

Reputation: 11255

Try to set offScreenPageLimit to View Pager.

viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);

Upvotes: 0

Uttam Panchasara
Uttam Panchasara

Reputation: 5865

You can do it like this if you want to Refresh/Notify your page.

do this whenever you want to refresh page.

yourPager.setAdapter(yourAdapter);
yourPager.setCurrentItem(CurrentPosition); // this is suppose to be your pagePosition 

this will Notify/Refresh your page.

Upvotes: 2

sonnv1368
sonnv1368

Reputation: 1597

Step1: Use addOnPageChangeListener listener

viewPagerSearch.addOnPageChangeListener(this);

Step2: Use callback

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //check position with index page to refresh that page

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

Upvotes: 0

Related Questions