Skip to content

Instantly share code, notes, and snippets.

@esabook
Created December 21, 2021 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esabook/950eeec910b65ef6b3f5c17aed79155d to your computer and use it in GitHub Desktop.
Save esabook/950eeec910b65ef6b3f5c17aed79155d to your computer and use it in GitHub Desktop.
Connect tabLayout to recycleView as ItemIndicator
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