如何在Android工作室中只执行一个内容选项卡?

时间:2018-03-19 09:22:11

标签: java android

当我按下标签3时,它会向标签0,标签1,标签2,标签3提供信息。 但是,它会显示选项卡3的正确内容。 我怎样才能执行标签3的内容?为什么它会执行其他页面?

private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainscreen);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);            
mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    } @Override
    public Fragment getItem(int position) {
        position = mViewPager.getCurrentItem();
        System.out.println("This is the currnet position : " + position);
        if (position == 0) {
            Tab0Index tab0 = new Tab0Index();
            Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();
            return tab0;
        } else if (position == 1) {
            Tab2Top10 tab2 = new Tab2Top10();
            Toast.makeText(getApplicationContext(), "tab2 active " + position, Toast.LENGTH_SHORT).show();
            return tab2;
        } else if (position == 2) {
            Tab3UserRanking tab3 = new Tab3UserRanking();
            Toast.makeText(getApplicationContext(), "tab3 active " + position, Toast.LENGTH_SHORT).show();
            return tab3;
        } else if (position == 3) {
            Tab4Profile tab4 = new Tab4Profile();
            Toast.makeText(getApplicationContext(), "tab4 active " + position, Toast.LENGTH_SHORT).show();
            return tab4;
        } else if (position == 4) {
            Tab5Setting tab5 = new Tab5Setting();
            Toast.makeText(getApplicationContext(), "tab5 active " + position, Toast.LENGTH_SHORT).show();
            return tab5;
        }else{
           return null;
        }
    @Override
    public int getCount() {
        // Show 5 total pages.
        return mNumOfTabs;
    } }}

1 个答案:

答案 0 :(得分:0)

请勿在{{1​​}}中使用Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();。选择页面时,视图页面已加载上一页和下一页。因此,将toast改为每个片段的onResume(Pages)。例如。对于Tab 1片段的onResume(),请使用下面的代码

SectionsPagerAdapter