【发布时间】:2020-08-24 13:41:34
【问题描述】:
我们可以在 TabLayout 下使用 Recyclerview 代替 ViewPager 吗? And, when a tab is selected, the content of the Recyclerview will be updated.
【问题讨论】:
标签: android android-recyclerview android-tablayout
我们可以在 TabLayout 下使用 Recyclerview 代替 ViewPager 吗? And, when a tab is selected, the content of the Recyclerview will be updated.
【问题讨论】:
标签: android android-recyclerview android-tablayout
你可以这样设置,添加需要的数量,在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) {
}
});
}
【讨论】:
我已经回答了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,它被设置为 customView 到 tabLayout:
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)
}
}
}
})
通过此设置,您可以:
【讨论】: