Reputation: 512
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:
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.
Upvotes: 3
Views: 1681
Reputation: 5319
I did nearly the same.
You can enable/disable view paging in the adapter via:
//disable viewpager
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
If you Load your Image use an AsyncTask
private class DownloadImageTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
Use the onPreExecute()
Method to disable viewpager, and in onPostExecute()
set the image and re-Enable the ViewPager
again.
This works perfectly for me
Upvotes: 2