重新选择选项卡时,片段为空白

时间:2017-01-05 12:10:44

标签: android android-fragments android-tablayout

最初,片段返回第一个和第二个标签的相应列表视图。但是返回第三个选项卡的空片段。当我再次选择第一个标签时,会显示空片段。 listadapter没问题 。当我在第二个选项卡中设置适配器时它工作正常。问题在于Mainactivity和Fragment

Mainactivity

public class SwipemainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener
{
private TextView displayTextView;
public static SwipemainActivity instance;

TabLayout tabLayout;
ViewPager viewPager;
Context context;
FragmentAdapterClass fragmentAdapter;

public static Context getInstance() {
    return instance;
}

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_swipemain);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    instance = this;

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    viewPager = (ViewPager) findViewById(R.id.viewpager);

    setSupportActionBar(toolbar);

    tabLayout.addTab(tabLayout.newTab().setText("NEW"));
    tabLayout.addTab(tabLayout.newTab().setText("CONFIRMED"));
    tabLayout.addTab(tabLayout.newTab().setText("FINISHED"));

    fragmentAdapter = new FragmentAdapterClass(getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(fragmentAdapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab LayoutTab) {

            viewPager.setCurrentItem(LayoutTab.getPosition());
        }


        @Override
        public void onTabUnselected(TabLayout.Tab LayoutTab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab LayoutTab) {

        }
    });
}
  }

片段

public class FragmentAdapterClass extends FragmentStatePagerAdapter {

int TabCount;

public FragmentAdapterClass(FragmentManager fragmentManager, int CountTabs) {
    super(fragmentManager);

    this.TabCount = CountTabs;

}

@Override
public Fragment getItem(int position) {

    switch (position) {

        case 0:
            Tab1 tab1 = new Tab1();
            return tab1;

        case 1:
            Tab2 tab2 = new Tab2();
            return tab2;

        case 2:
            Tab3 tab3 = new Tab3();
            return tab3;

        default:

        return null;
    }
}

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

}

1 个答案:

答案 0 :(得分:3)

我从不使用此侦听器来更改viewpager片段。并使用setOffScreenPageLimit告诉viewpager需要在内存中保存多少个片段。这就是我总是使用tabbedlayout和viewpager设置片段的方式。

viewPager.setOffscreenPageLimit(AMOUNT_OF_FRAGMENTS);