我想使用ViewPager和包含和管理RecyclerView的片段来实现简单的滑动导航。
片段已创建并可以使用setCurrentItem()
进行切换,但无法向左或向右滑动以切换页面。 ViewPager似乎忽略任何滑动手势。
我的Activity布局:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"/>
<android.support.v7.widget.Toolbar
... />
</FrameLayout>
我在我的onCreate()
中使用FragmentPagerAdapter
来填充ViewPager:
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.addOnPageChangeListener(this);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Dummy2Fragment();
case 1:
return new Dummy2Fragment();
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
return "Dataset " + (position + 1);
}
});
片段布局是一个简单的FrameLayout
,它包装了一个RecyclerView:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_material_light"/>
</FrameLayout>
在片段的onCreateView
方法中设置适配器和布局管理器:
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 6, LinearLayoutManager.VERTICAL, false));
编辑 #1
我觉得我的问题没有表述清楚。
我有一个工作的 Pager 和一个工作的 TabLayout,由“FragmentPagerAdapter”填充,这意味着 Fragment 被正确创建,而选项卡布局显示了每个项目的可点击选项卡。此 ViewPager 中的每个 Fragment 都显示了一个使用 GridLayoutManager 的 RecyclerView。
然而,ViewPager 似乎没有接收到任何滑动手势,您可以通过 TabLayout 更改当前选择的位置,但例如从左向右滑动则不行。
看起来 RecyclerView 占用了所有滑动事件,无论布局方向如何,这是设置为“vertical”的。
有什么想法吗?