inside an activity I have an observer I am calling a function to setup adapter. After that I am setting list to my adapter. And doing How to know when the RecyclerView has finished laying down the items?. And setting layout manager on that. But it's not working.
activity.kt
class activity : BaseActivity() {
private var cAdapter: cdAdapter? = null
fun setupObserver(){
viewModel.list.observe(this, { value ->
if (cAdapter == null) {
setupAdapter()
}
submitList(value)
binding.cRecyclerView.afterMeasured {
layoutManager = LinearLayoutManager(this.context).apply {
direction(this)
}
}
})
}
private fun setupAdapter() {
cAdapter = cdAdapter()
binding.cRecyclerView.adapter = cAdapter
}
private fun direction(linearLayoutManager: LinearLayoutManager) {
linearLayoutManager.apply {
// if (binding.cRecyclerView.canScrollVertically(1)) {
// logE("Yes can scroll")
//} else {
// logE("No scroll")
// }
if (viewModel.itemsAreMorethanTwo()) {
stackFromEnd = true
reverseLayout = true
val index = viewModel.findLastBiggerValue()
if (index != null && index >= 0) {
scrollToPosition(index)
}
} else {
stackFromEnd = false
reverseLayout = true
}
}
}
inline fun <T : View> T.afterMeasured(crossinline f: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
f()
}
}
})
}
}
Basically inside direction
function I am checking that if item has more than two value, i'm using reverse layout as well as stackFromEnd as true. As you see inside direction
function some lines are commented and I need to check that my items are less than the whole height, i.e. I don't want to scroll up or down and the whole items consist in a single screen
For the commented section, I want to know if the view is scrollable or not.
the code below is working and above code is not.
If I move this code from observer
binding.cRecyclerView.afterMeasured {
layoutManager = LinearLayoutManager(this.context).apply {
direction(this)
}
}
inside like this
private fun setupAdapter() {
cAdapter = cdAdapter()
binding.cRecyclerView.apply {
adapter = cAdapter
layoutManager = LinearLayoutManager(this.context).apply {
setLayoutDirection(this)
}
}
}
When I move this piece of code in setupAdapter the commented section does not work though it sets the layout manager correctly. What I am doing wrong in above code? Please suggest me something.