Created
December 21, 2021 09:33
-
-
Save esabook/950eeec910b65ef6b3f5c17aed79155d to your computer and use it in GitHub Desktop.
Connect tabLayout to recycleView as ItemIndicator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun TabLayout.asItemIndicator(recyclerView: RecyclerView) { | |
//setup tab as dot indicator | |
removeAllTabs() | |
recyclerView.adapter?.itemCount?.downTo(1)?.forEach { _ -> | |
addTab(newTab()) | |
} | |
//make tabActiveIndex as/jump rvAdapterIndex | |
addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { | |
override fun onTabSelected(tab: TabLayout.Tab?) { | |
try { | |
recyclerView.smoothScrollToPosition(tab!!.position) | |
} catch (e: Exception) { | |
} | |
} | |
override fun onTabUnselected(tab: TabLayout.Tab?) { | |
} | |
override fun onTabReselected(tab: TabLayout.Tab?) { | |
} | |
}) | |
//make rvScrollIndex sync witch tabActiveIndex | |
recyclerView.clearOnScrollListeners() | |
LinearSnapHelper().attachToRecyclerView(recyclerView) | |
val rvScrollListener = object : RecyclerView.OnScrollListener() { | |
override fun onScrollStateChanged(rv: RecyclerView, newState: Int) { | |
try { | |
// find active page (which should be highlighted) | |
val activePosition = (rv.layoutManager as LinearLayoutManager) | |
.findFirstCompletelyVisibleItemPosition() | |
val tab = getTabAt(activePosition) | |
selectTab(tab, true) | |
} catch (e: Exception) { | |
} | |
} | |
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) { | |
try { | |
val lm = (rv.layoutManager as LinearLayoutManager) | |
val activePosition = lm.findFirstCompletelyVisibleItemPosition() | |
setScrollPosition( | |
activePosition, | |
0F, | |
false, | |
true | |
) | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} | |
} | |
recyclerView.addOnScrollListener(rvScrollListener) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment