Set default page for ViewPager in Android

前端 未结 5 2073
孤独总比滥情好
孤独总比滥情好 2020-11-30 02:04

I am using the following code, MAX is 2 pages. By default the position is 0 and adds a new page to the right. I inflate two layout files.

How can I show the page1 wh

相关标签:
5条回答
  • 2020-11-30 02:45

    This solution gives the ability of setting default page without interference from outside of the Pager adapter class.

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View currentPage = null;
        switch(position){
            case 0:
                currentPage = LayoutInflater.from(context).inflate(R.layout.page0, null)    
                break;
            case 1:
                currentPage = LayoutInflater.from(context).inflate(R.layout.page1, null)    
                ///////////// This page will be default ////////////////////
                ((ViewPager)container).setCurrentItem(position);
                ////////////////////////////////////////////////////////////
                break;
            case 2:
                currentPage = LayoutInflater.from(context).inflate(R.layout.page2, null)    
                break;
        return currentPage;
    }
    
    0 讨论(0)
  • 2020-11-30 02:48

    Have you tried using the setCurrentItem method?

    0 讨论(0)
  • 2020-11-30 02:48

    The accepted solution is fine, but it's important to call this method after setting up the adapter.

        viewPager.setAdapter(adapterViewPager);
        viewPager.setCurrentItem(1);
    
    0 讨论(0)
  • 2020-11-30 02:48

    You need to set page only during first initialisation of the fragment. Later it will restore a selected by user position from a "saved instance state". So this looks a little better:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        pager.adapter = AwesomePagerAdapter()
        if (savedInstanceState == null) {
            pager.currentItem = 1
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:58

    By default, you have to set the current value 1 to show the just one default view. If you do not set setCurrentItem to 1, you can not see anything.

    viewPager.setAdapter(adapterViewPager);
    viewPager.setCurrentItem(1)
    
    0 讨论(0)
提交回复
热议问题