每次重新选择选项卡时,viewpager tablayout中的片段都会保持不变

时间:2016-02-29 13:05:53

标签: android android-fragments android-viewpager android-tablayout

我有三个标签,当用户转到第三个标签然后回到第一个标签时 - 第一个标签中的内容不会重置,表单会不断重新加载。

这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scorespagemain);
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    CAdapter cAdapter = new Adapter(getSupportFragmentManager(), ScoresPageMain.this);
    viewPager.setAdapter(cAdapter);
    tabLayout = (TabLayout) findViewById(R.id.tabsstuff);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

}

CAdapter上课:

public class CAdapter extends FragmentPagerAdapter{
    String names[] = new String[] {"Top Teams", "Top Scores", "Top Players"};
    Context context;

    public CAdapter(FragmentManager fragmentManager, Context context){
        super(fragmentManager);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new TopTeams();
            case 1:
                return new TopScores();
            case 2:
                return new TopPlayers();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return names[position];
    }
}

1 个答案:

答案 0 :(得分:5)

尝试在代码中使用setOffscreenPageLimit()

希望这会对你有所帮助。