I am using a ViewPager so the user can browse through an infinite collection of images that need to be fetched from the Internet.
I would not like to change to the next/previous page, unless its image has already been loaded. So if the user swiped right/left, the current image would still be on display with a progressbar spinning on top, and the change to the next/previous page would not be performed until the image was ready. At that very instant pages would swap and the progressbar would disappear.
At the moment I was trying to implement this using the following layout for the children views of the ViewPager and a FragmentStatePageAdapter.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="@string/label_painting"
android:visibility="gone" />
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" android:visibility="gone" />
</FrameLayout>
In the Fragment I follow the steps listed below:
- In its onCreateView I make the progressbar visible.
- In that same method I start a thread that fetches the image and decodes the byte stream into a bitmap.
- Once the bitmap is available, the thread sends a message to a handler that sets the bitmap in the ImageView, makes it visible and hides the progressbar.
The problem with this approach I am following is that in case the image has not been fetched yet when the user swipes, the previous image disappears and he sees a spinning progressbar until the new image is available. It would be much nicer to keep seeing an image.
Has anyone been able to implement this with a ViewPager or knows what could I change in my code?
Thanks in advance.