How to tell RecyclerView to start at specific item position

前端 未结 6 2033
难免孤独
难免孤独 2021-02-20 10:43

I want my RecyclerView with LinearLayoutManager to show up with scroll position at specific item after adapter got updated. (not first/last position) Means the at first (re-)lay

6条回答
  •  清歌不尽
    2021-02-20 11:20

    None of the methods above worked for me. I did the following using ViewTreeObserver that is triggered once its children have been added/changed visibility.

    recyclerView.apply {
       adapter = ...
       layoutManager = ...
    
       val itemCount = adapter?.itemCount ?: 0
       if(itemCount > 1) {
          viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
          override fun onGlobalLayout() {
             viewTreeObserver.removeOnGlobalLayoutListener(this)
             (layoutManager as? LinearLayoutManager)?.scrollToPosition(#PositionToStartAt)
          }
       }
    }
    

    Go ahead and set #PositionToStartAt to a specific value. You can also ensure that the RecyclerView initial position setting gets triggered once a specific number of children have been laid out to ensure it is set correctly.

    if(recyclerView.childCount() > #PositionCheck) {
       viewTreeObserver.removeOnGlobalLayoutListener(this)
       (layoutManager as? LinearLayoutManager)?.scrollToPosition(#PositionToStartAt)
    }
    

提交回复
热议问题