onPageSelected doesn't work for first page

前端 未结 10 1993
[愿得一人]
[愿得一人] 2021-01-30 12:30

My pager adapter ( extends PagerAdepter ) has a textview in it. And I update this textview with MainActivity\'s onPageSelected . Its update textview for position > 0 , but start

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 13:19

    My solution was to extend pager adapter and create an interface inside it. Then make the adapter call the interface only once after creating the adapter. Inside interface callback you can call onPageChanged method without having nullpointerexception. Add this class to your project and extend your adapter from it. Dont forget to set listener to adapter before setting adapter to viewpager. Adapter class below:

    public abstract class ExtendedPagerAdapter extends FragmentPagerAdapter {
    
    private boolean instantiated;
    private AdapterListener adapterListener;
    
    public interface AdapterListener {
        void onAdapterInstantiated();
    }
    
    public ExtendedPagerAdapter(FragmentManager fragmentManager) {
        this(fragmentManager, null);
    }
    
    public ExtendedPagerAdapter(FragmentManager fragmentManager, AdapterListener adapterListener) {
        super(fragmentManager);
        this.adapterListener = adapterListener;
        instantiated = false;
    }
    
    @Override
    public void finishUpdate(ViewGroup container) {
        super.finishUpdate(container);
        if (!instantiated) {
            instantiated = true;
            if (adapterListener != null) {
                adapterListener.onAdapterInstantiated();
            }
        }
    }
    
    public void setAdapterInstantiatedListener(AdapterListener adapterListener) {
        this.adapterListener = adapterListener;
    }
    }
    

提交回复
热议问题