我需要在TabLayout
中放置ViewPager
。 ViewPager
包含一些片段。我不能这样做,因为TabLayout
位于我的Activity
中,如果它位于Fragment
,我就无法管理它。
现在我的代码看起来像这样。在Activity
的XML中:
<LinearLayout
...>
<android.support.v4.view.ViewPager
...>
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
.../>
</LinearLayout>
并在Activity
类
ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager_offer_detail);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabDots);
tabLayout.setupWithViewPager(mViewPager, true);
FragmentPagerAdapter mPagerAdapter = new FragmentPagerAdapter(...);
mViewPager.setAdapter(mPagerAdapter);
我需要得到如下所示。
what i want(imgur现在不起作用)
哪个版本是正确的以及如何在XML中实现它?
答案 0 :(得分:0)
如果我理解,您想在tabs
权限内显示一些Fragments
(ViewPager
)吗?
您可以在片段中遵循此实现:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_tablayout, container, false);
TabLayout tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Campusplan"));
tabLayout.addTab(tabLayout.newTab().setText("Raumplan"));
final ViewPager viewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter
(getFragmentManager(), tabLayout.getTabCount()));
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) {
}
});
return inflatedView;
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabItem1 tab1 = new TabItem1();
return tab1;
case 1:
TabItem1 tab2 = new TabItem1();
return tab2;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
}
将tablayout和viewpager放在layout.xml中,代表您的片段,就像使用普通视图一样。