jpihl jpihl - 2 months ago 10
Android Question

onPageSelected isn't triggered when calling setCurrentItem(0)

I have an Activity with a ViewPager which displays a bunch of pictures. When it starts the ViewPager's position is set based on what the user selected in a previous Activity. Similar to a gallery.

I want the onPageSelected to be called every time a new page is selected, i.e. when the Activity is first opened or when the user slides to a new page.

I set the starting point like so:

mPager.setCurrentItem(index);


Everything works, except when setCurrentItem called with index set to 0 as this will not trigger onPageSelected.

mPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int index) {
Log.d(TAG, "onPageSelected " + index);
}
...
}


So my question is; is this a bug, and if so what can I do about it?

Answer

Ok, so I haven't been able to figure out whether this is a bug (or a feature). But I thought I'd share how a possible solution to the problem could look..

Write the functionality you wish to perform in a method in the Activity and then call this in the onPageSelected method.

mPager.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int index) {
        myOnPageSelectedLogic(index);
    }
    ...
}

And then right after calling

setCurrentItem(index);

in the Activity, add the following if statement

if(index == 0) {
    myOnPageSelectedLogic(0);
}

It's not super pretty but I hope it helps someone :)

Comments