How can make my ViewPager load only one page at a time ie setOffscreenPageLimit(0);

Solution 1:

I was having the same problem and I found the solution for it:

Steps:

1) First Download the CustomViewPager Class from this link.

2) Use that class as mentioned below:

In Java:

CustomViewPager mViewPager;
mViewPager = (CustomViewPager) findViewById(R.id.swipePager);
mViewPager.setOffscreenPageLimit(0);

In XML:

<com.yourpackagename.CustomViewPager 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipePager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Now only one page will be loaded at once.

P.S: As per the question's requirement, I have posted the solution for Viewpager. I haven't tried the same with TabLayout yet. If I will find any solution for that I will update the answer.

In this file, KeyEventCompat is used it may not found by the android studio because KeyEnentCompat class was deprecated in API level 26.0.0 so you need to replace KeyEventCompat to event for more details you can view https://developer.android.com/sdk/support_api_diff/26.0.0-alpha1/changes/android.support.v4.view.KeyEventCompat

Solution 2:

As far as I know, that is not possible when using the ViewPager. At least not, when you want your pages to be swipe-able.

The explaination therefore is very simple:

When you swipe between two pages, there is a Point when both pages need to be visible, since you cannot swipe between two things when one of those does not even exist at that point.

See this question for more: ViewPager.setOffscreenPageLimit(0) doesn't work as expected

CommonsWare provided a good explaination in the comments of his answer.

Solution 3:

but I need to load one page at a time because memory problems.

That presumes that you are getting OutOfMemoryErrors.

Am i going to have to use the old style tabhost etc?

Yes, or FragmentTabHost, or action bar tabs.

or is there a way/hack I can make my viewPager load one page at a time?

No, for the simple reason that ViewPager needs more than one page at a time for the sliding animation. You can see this by using a ViewPager and swiping.

Or, you can work on fixing your perceived memory problems. Assuming this app is the same one that you reported on earlier today, you are only using 7MB of heap space. That will only result in OutOfMemoryErrors if your remaining heap is highly fragmented. There are strategies for memory management (e.g., inBitmap on BitmapOptions for creating bitmaps from external sources) that help address such fragmentation concerns.

My Adapter extends BaseAdapter with the ViewHolder patern.

BaseAdapter is for use with AdapterView, not ViewPager.