scroll recyclerview item to top inside of scroll view

扶醉桌前 提交于 2021-01-29 09:09:56

问题


I'm trying to scroll recycler view item to top of screen when user clicks on an item.

My layout is set as following

- <FrameLayout>
--   <ScrollView>
---     <LinearLayout /> // static content
---     <RecyclerView /> // dynamic content
---     <LinearLayout /> // static content
--   </ScrollView>
-- </FrameLayout>

What I want to achieve is when i click on an item of recyclerview. It should scroll up to top of the screen.

I have tried following so far but no luck.

-> 
  // use recycler view's layout manager to scroll.
  recyclerView.layoutManager.scrollToPositionWithOffset(position)

->
 // use smooth scroll to scroll
 recyclerView.smoothScrollToPosition(ItemPos)

->
  // use main scroll view to scroll on the screen. This kind of works but does not move item to top of the page.
  val y = recyclerView.y + recyclerView.getChildAt(position).y
  activity.binding.mainScrollview?.smoothScrollTo(0, y.toInt())

Any help is appreciated. Thank you


回答1:


Looks like in your case you don't have enough items.

You can't get recyclerView scroll lower than the last Item So it's either you make your own implementation of recyclerView by extending it,get add scroll amounts and when got to the last item you'll add up the translationY of the recyclerView.

Or you can add a few dummy Items.So they can be View with width and height of your normal Items.That should do it.




回答2:


Have you tried layoutManager's scrollToPositionWithOffset function:

thirdItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView
                    .getLayoutManager();
            layoutManager.scrollToPositionWithOffset(0, 0);
        }
});


来源:https://stackoverflow.com/questions/54696408/scroll-recyclerview-item-to-top-inside-of-scroll-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!