Android: get the exact position on the screen that the user was at in a recyclerview

不想你离开。 提交于 2019-12-08 04:53:31

问题


I'm going to reference the following question, because this person asked the same thing a month ago but nobody has answered him yet:

How to scroll the user at the exact position, which is somewhere between two views.?

When the user scrolls somewhere inside a recyclerview list and minimizes the app, then restores it from the bg - or goes into another activity/fragment and returns back to the recyclerview - I want the list to scroll to the exact same location the user was at. When I say the exact location I mean it has to be the exact same location - if I just tell the app to scroll to position X, then the topmost view will be at the top, but it won't be the same exact list state as the user had before. I need the list to look identical to the way it looked before the user left and returned. Is this possible, and if so, how?

My current code:

viewHolder.objectInTheList.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        if (recyclerViewInterface != null) {

                            FileAccessUtil.getInstance().setIntegerProperty("recyclerListPosition", position);
                            recyclerViewInterface.onRecyclerviewListEventOccured(position);

                        }
                    }

            });

and then when I return to the activity I load that parameter from fileaccessutil and do:

 recyclerlist.scrollToPosition(positionFromFileAccessUtil);

This solution is suboptimal because, as I mentioned before, it doesn't scroll the user to the exact identical screen position that he was at before.


回答1:


Have you looked at RecyclerView.ScrollBy(x,y)?

ScrollBy(0,y) will scroll the RecyclerView in the same direction as it would if you were to move your finger up. It won't scroll to an absolute position, instead, it will just add pixels to the previous scroll position. To scroll in the opposite direction, simply use ScrollBy(0,-y). Notice that x is set to zero because you only want to scroll up/down.

Now, in order to achieve a complete solution, you will need to have a way to save the list's current scroll position. I did not test it, but I am pretty sure that RecyclerView.getScrollY() will always return 0. To overcome this, you will need to track the position yourelf by listening for scroll changes to the RecyclerView.

When you want to restore the scroll position, you can use your saved current position since the RecyclerView will, initially, have a scroll value of 0.



来源:https://stackoverflow.com/questions/32972184/android-get-the-exact-position-on-the-screen-that-the-user-was-at-in-a-recycler

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