简体   繁体   中英

Scroll two Views at the same time

The idea first: I'm trying to scroll two Views at the same time. Means, when you scroll the first one, the second one will scroll at the same time. The layout is following:

在此处输入图片说明

The reality: I have two lists one is horizontal and another one is vertical. The horizontal one contains a list of categories, and the vertical one contains images from those categories. Category 1, Category 2 and Category 3 are items of a RecyclerView. RV1, RV2 and RV3 are three horizontal recyclerviews. Currently I'm putting those "RV1, RV2 and RV3" in a vertical LinearLayout which has a vertical ScrollView parent. I'm not sure if I should replace this linearlayout and scrollview with a recyclerview. But the idea remains the same, I need to scroll the other list when one is being scrolled by user.

To be more specific

  1. When I scroll the category horizontal list and bring the "Category 2" at the left most position the "RV 2" in the vertical list should be at the top most position.
  2. The same happens if I do with the vertical list. If I scroll "RV 1" to the top, the "Category 1" should also be scrolled automatically and be at the left most position.
  3. The "RV1, RV2 and RV3" recyclerviews can horizontally scroll by themselves, that's fine, that's not an issue.

You should be able to model the desired behavior as follows:

Add an onScrollListener to the horizontal category RecyclerView. Then inside onScrolled , you can determine the left most item using firstVisibleItemPosition or firstCompletelyVisibleItemPosition based on your exact needs. (links are for a LinearLayoutManager, which is mostly what you're using there)

Note : onScrolled is called after the user finishes scrolling, so if you need live scrolling you can try doing something similar inside onScrollStateChanged .

Regardless, you'll now have an int corresponding to the position of the leftmost category, which maps directly to the position of corresponding RV that needs to be brought to the top.

I'd recommend switching your ScrollView and LinearLayout combination to a RecyclerView, because it would be much simpler to scroll to a particular item. You can pass the index retrieved earlier to the smoothScrollToPosition or scrollToPosition method of this vertical RecyclerView, depending on how the content should be scrolled.

You can do the same thing with the vertical RV in order to automatically scroll the Categories. If I recall correctly, the programmatic scrollToPosition calls did not trigger any attached onScrollListener s. If this has changed, then you will have to ensure they don't keep scrolling each other unnecessarily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM