选项卡布局和视图分页器中的选项卡布局和视图分页器

时间:2016-07-17 16:03:57

标签: android android-viewpager

在我的主要活动中,我创建tablayout并查看寻呼机,然后当我切换到选项卡B(选项卡A到选项卡B)和选项卡B内部时,我创建了另一个选项卡布局和viewpager但内容变为空,只有选项卡名称为显示。请指导我这个问题。这是我在选项卡B中的代码:

public class TabB extends BaseFragment {

private TabLayout tabLayout;
private ViewPager viewPager;

@Override
public int getLayoutResourceId() {
    return R.layout.fragmentB;
}

@Override
public void initView(View view) {
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    tabLayout = (TabLayout) view.findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewChildPagerAdapter adapter = new ViewChildPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new TabC, "tab c");
    adapter.addFragment(new TabD, "tab d");
    viewPager.setAdapter(adapter);
}

public static class ViewChildPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mTitle = new ArrayList<>();

    public ViewChildPagerAdapter(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, String title) {
        mFragmentList.add(fragment);
        mTitle.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitle.get(position);
    }


}

}

1 个答案:

答案 0 :(得分:-2)

我没有看到你的观点在单独的片段中创建一个新的tablayout。为什么不在Activity上创建TabLayouts?然后你只需要拨打setupWithViewPager()一次。