我的应用程序中有三个选项卡片段,当应用程序启动时,索引0 onCreate上的选项卡被调用,选项卡ta索引1 onCreateView方法未被调用。我需要更新选项卡1 onCreate方法中的UI。我该如何解决这类问题。
代码:
private void setupViewPager(ViewPager viewPager) {
adapter.addFragment(new Users());
adapter.addFragment(new FavouriteUsers());
adapter.addFragment(new Recent());
viewPager.setAdapter(adapter);
}
页面适配器代码:
public class UserPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public UserPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
答案 0 :(得分:1)
尝试使用getChildFragmentManager()来初始化UserPagerAdapter
UserPagerAdapter adapter = new UserPagerAdapter(getChildFragmentManager())
如果这不起作用,请尝试将FragmentStatePagerAdapter更改为 FragmentPagerAdapter 。
答案 1 :(得分:0)
像这样实施你的getItem(int position)
。
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Users tab1 = new Users();
return tab1;
case 1:
FavouriteUsers tab2 = new FavouriteUsers();
return tab2;
case 2:
Recent tab3 = new Recent();
return tab3;
default:
return null;
}
}
并在您的标签活动中调用适配器,如此
final UserPagerAdapter adapter = new UserPagerAdapter
(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});