ViewPager嵌套ViewPager
时间: 2023-10-24 22:12:36 浏览: 103
ViewPager 嵌套
5星 · 资源好评率100%
ViewPager嵌套ViewPager的实现可以通过使用Fragment来实现。具体步骤如下:
1. 创建外层ViewPager的适配器,内层ViewPager的适配器和内层ViewPager的Fragment适配器;
2. 在外层ViewPager的Fragment中创建内层ViewPager,并设置内层ViewPager的适配器为内层ViewPager的适配器;
3. 在内层ViewPager的Fragment中创建需要的子Fragment,并设置内层ViewPager的Fragment适配器为子Fragment的适配器。
代码示例:
```java
public class OuterFragment extends Fragment {
private ViewPager mInnerViewPager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_outer, container, false);
mInnerViewPager = view.findViewById(R.id.inner_view_pager);
InnerPagerAdapter innerPagerAdapter = new InnerPagerAdapter(getChildFragmentManager());
mInnerViewPager.setAdapter(innerPagerAdapter);
return view;
}
private class InnerPagerAdapter extends FragmentPagerAdapter {
public InnerPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return InnerFragment.newInstance(position);
}
@Override
public int getCount() {
return 3;
}
}
}
public class InnerFragment extends Fragment {
private ViewPager mSubViewPager;
public static InnerFragment newInstance(int position) {
InnerFragment fragment = new InnerFragment();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inner, container, false);
mSubViewPager = view.findViewById(R.id.sub_view_pager);
SubPagerAdapter subPagerAdapter = new SubPagerAdapter(getChildFragmentManager());
mSubViewPager.setAdapter(subPagerAdapter);
return view;
}
private class SubPagerAdapter extends FragmentPagerAdapter {
public SubPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return SubFragment.newInstance(position);
}
@Override
public int getCount() {
return 3;
}
}
}
public class SubFragment extends Fragment {
public static SubFragment newInstance(int position) {
SubFragment fragment = new SubFragment();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sub, container, false);
return view;
}
}
```
其中,fragment_outer.xml、fragment_inner.xml和fragment_sub.xml分别对应外层ViewPager的Fragment、内层ViewPager的Fragment和内层ViewPager的子Fragment的布局文件。
阅读全文