如何在android中显示片段

时间:2016-07-05 02:56:23

标签: android android-fragments android-viewpager

我正在使用ViewPager在Activity1上创建3个片段,
这是我的viewPager适配器:

 public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                Fragment1 tab1 = new Fragment1();
                return tab1;
            case 1:
                Fragment2 tab2 = new Fragment2();
                return tab2;
            case 2:
                Fragment3 tab3 = new Fragment3();
                return tab3;
            default:
                return null;
        }
    }

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

}

这是活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_1);

    TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
    tab_layout.addTab(tab_layout.newTab().setText("Frag1"));
    tab_layout.addTab(tab_layout.newTab().setText("Frag2"));
    tab_layout.addTab(tab_layout.newTab().setText("Frag3"));

    final ViewPager view_pager = (ViewPager) findViewById(R.id.viewpager);

    final ViewPagerAdapter adapter = new ViewPagerAdapter
            (getSupportFragmentManager(), tab_layout.getTabCount());

    view_pager.setAdapter(adapter);

    view_pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_layout));

    tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            view_pager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });

}

当Activity1打开时,它显示Fragment1。但我想改为展示Fragment2或Fragment3 我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

viewpager.setAdapter(adapter);之后添加此行:

viewPager.setCurrentItem(index);

索引取决于您,您拥有多少片段。 tabLayout.getTabCount();会返回标签计数。但索引从0开始。

如果您有3个Fragment并希望显示第三个Fragment,则必须使用viewPager.setCurrentItem(2);

答案 1 :(得分:1)

将viewpager的当前位置设置为您想要的位置,在您的情况下为2或3。

 new Handler().post(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(desiredPos);
                }
            });

见更多

Android ViewPager setCurrentItem not working after onResume