我想构建下一个UI:
带有2个选项卡和2个不同片段的TabLayout(已解决和未解决)
我永远不会调用片段中的onCreateView。
这里我给viewPager充气:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());
viewPager.setAdapter(mAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(viewPager);
mTabLayout.getTabAt(0).setText(getString(R.string.tablayout_unsolved));
mTabLayout.getTabAt(1).setText(getString(R.string.tablayout_solved));
}
我的自定义ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
if (!mFragmentList.isEmpty() && mFragmentList.size() > id)
return mFragmentList.get(position);
return new Fragment();
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
这是我片段的一个例子:
public class SolvedTasksFragment extends Fragment implements RecyclerViewClickListenerSolved {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Some code here;
return rootView;
}
@Override
public void itemClick(View v, int position) {
}
}
也许有人能分辨出什么是错的 我不需要整个解决方案。
答案 0 :(得分:1)
id
的值为16842960
所以
if (true && 2 > 16842960) // will not be executed
// true && false => false
解决方案:您可以针对position
检查尺寸,或者如果不是特定于实施,则删除此检查
@Override
public Fragment getItem(int position) {
if (mFragmentList.size() > position)
return mFragmentList.get(position);
return new Fragment();
}
答案 1 :(得分:1)
首先设置适配器,然后添加片段。像这样做。 更改这些陈述
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());
viewPager.setAdapter(mAdapter);
到这些
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
mAdapter.addFragment(new UnsolvedTasksFragment());
mAdapter.addFragment(new SolvedTasksFragment());