recyclerview

RecyclerView和ViewPager结合使用

小樊
167
2024-06-19 10:28:04
栏目: 编程语言

你可以在ViewPager中放置一个包含多个RecyclerView的Fragment,这样就可以在ViewPager的每个页面中显示不同的RecyclerView。以下是一个简单的示例代码:

  1. 创建一个包含RecyclerView的Fragment:
public class MyRecyclerViewFragment extends Fragment {

    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;

    public MyRecyclerViewFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        
        adapter = new RecyclerViewAdapter();
        recyclerView.setAdapter(adapter);

        return view;
    }
}
  1. 创建一个包含ViewPager和多个MyRecyclerViewFragment的Activity:
public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewPager);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new MyRecyclerViewFragment();
        }

        @Override
        public int getCount() {
            return 3; // 3个页面
        }
    }
}
  1. 创建RecyclerView的布局文件 fragment_recycler_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. 创建ViewPager的布局文件 activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

通过以上代码,你可以在ViewPager的每个页面中显示不同的RecyclerView,从而实现RecyclerView和ViewPager的结合使用。

0
看了该问题的人还看了