lyricat lyricat - 3 years ago 442
Android Question

ViewPager onPageSelected for first page

So it appears that when using a ViewPager, the onPageSelected listener does not get called for the first page same issue as this.

I have some logic that populates some more expensive UI elements for the currently selected page and this works when page is changed, but

it doesn't work for the first page.

If I set the current item after the listener, the callback gets fired for the first page, but the view has not been initialized yet, so I can't manipulate it:

// Inside PagerAdapter.instantiateItem

ViewHolder vh = new ViewHolder();
vh.view = adapter.newView(context, cursor, null);
// Set position as tag so we can retrieve it with findViewByTag

((ViewPager) collection).addView(vh.view,0);

return vh;

// Inside MyActivity.onCreate

pagerAdapter = new SingleMessagePagerAdapter(this, cursor);
pager = (ViewPager)findViewById(;

// Inside MyActivity.onPageSelected

// Retrieve tagged view
View view = pager.findViewWithTag(position);

ends up being null because
has not yet been run. So I guess my question is, at which point in the activity lifecycle can I be certain that the ViewPager has initialized the view? I tried doing this inside
but it appears both of these get fired before

Answer Source

try to use fragments!

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter() {

    public Fragment getItem(int i) {
        Fragment fr = null;
        if (i==0)
           fr = new sec0frag();
        else if (i==1)
           fr = new sec1frag();
        else if (i==2)
           fr = new sec2frag();
        return fr;

    public int getCount() {
        return 3;

and create 3 fragments classes

e.g. :

    public static class sec0frag extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
                     // here is initialize for first time to view pages.!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download