我想建立下一个用户界面:
具有2个标签和2个不同片段的TabLayout(已解决和未解决)
我的Fragment中的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) {
}
}
也许有人可以说出问题所在。
我不需要整个解决方案。
最佳答案
首先设置适配器,然后添加片段。像这样做。
更改这些陈述
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());