将RecyclerView与TabLayout同步

时间:2018-03-30 09:58:44

标签: android android-recyclerview android-tablayout

我们可以在其下面使用带有Recyclerview的TabLayout而不是ViewPager吗?并且,选择选项卡后,将更新Recyclerview的内容。

2 个答案:

答案 0 :(得分:1)

你可以像这样设置,添加所需的数量,在RecycleView的初始数据中为0位置然后添加addOnTabSelectedListener并在根据它更改Tab时更新列表'的立场

 private TabLayout tabLayout;
 private MyAdapter myAdapter;
 private List<MyObject> list;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        list=new ArrayList<>();
        myAdapter=new MyAdapter(this,list);

        RecyclerView recyclerViewOrderList = view.findViewById(R.id.recyclerViewOrderList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerViewOrderList.setLayoutManager(layoutManager);
        recyclerViewOrderList.setAdapter(myAdapter);

        TabLayout.Tab tab1 = tabLayout.newTab();
        tab1.setText("TAb1");

        TabLayout.Tab tab2 = tabLayout.newTab();
        tab1.setText("TAb1");
        tabLayout.addTab(tab1);
        tabLayout.addTab(tab2);


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                switch (tab.getPosition()) {

                    case 0:
                        //list 
                        // setup adapter for position 0
                        break;
                    case 1:
                        // setup adapter for position 1
                        break;
                }


            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
}

答案 1 :(得分:1)

我已经回答了here,但是对于这个问题,将其重复也可能与之相关:

足以覆盖RecyclerView的onScrolled并选择选项卡,并在选择选项卡且尚未选择该选项卡时滚动到位置:

override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
     val llm = recyclerView.layoutManager as LinearLayoutManager

     // depending on sections'heights one may want to add more logic 
     // on how to determine which section to scroll to
     val firstCompletePos = llm.findFirstCompletelyVisibleItemPosition()

     if (firstCompletePos != tabLayout.selectedTabPosition)
         tabLayout.getTabAt(firstCompletePos)?.select()
}

然后我有一个TextView,它设置为tabLayout的customView:

tabLayout.addTab(newTab().also { tab ->
         tab.customView = AppCompatTextView(context).apply {
             // set layout params match_parent, so the entire section is clickable
             // set style, gravity, text etc.
             setOnClickListener { 
                tabLayout.selectTab(tab)

                recyclerView.apply {
                    val scrollTo = tabLayout.selectedTabPosition
                    smoothScrollToPosition(scrollTo)
                }
             }
          }
})

使用此设置,您可以:

  1. 用户同时滚动和猛击时选择制表符
  2. 当用户单击选项卡时,RecyclerView会滚动。