lyricat lyricat - 1 month ago 33
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();
cursor.moveToPosition(position);
vh.view = adapter.newView(context, cursor, null);
// Set position as tag so we can retrieve it with findViewByTag
vh.view.setTag(position);

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

return vh;

// Inside MyActivity.onCreate

pagerAdapter = new SingleMessagePagerAdapter(this, cursor);
pager = (ViewPager)findViewById(R.id.message_pager);
pager.setAdapter(pagerAdapter);
pager.setOnPageSelectedListener(this);
pager.setCurrentItem(selectedItem);

// Inside MyActivity.onPageSelected

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


Here
view
ends up being null because
PagerAdapter.instantiateItem
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
Activity.onAttachedToWindow
and
Activity.onResume
but it appears both of these get fired before
PagerAdapter.instantiateItem
.

Answer

try to use fragments!

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter() {
        super(getSupportFragmentManager());
    }

    @Override
    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;
    }

    @Override
    public int getCount() {
        return 3;
    }
}

and create 3 fragments classes

e.g. :

    public static class sec0frag extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
                     // here is initialize for first time to view pages.!
        }
    }