3

I am currently using a ListView to display some data. Due to the design, the rows take up about 70% of the height of the screen which means there is always at least 2 rows visible, with a max of three. What I would like to determine is which row is mostly visible.

I am currently using onChangeVisibleRows, but that just tells me which rows are visible or have entered or left the view.

Any ideas?

doostin
  • 237
  • 2
  • 11

2 Answers2

2

This will only work when you know there are 2-3 (no more, no less) rows visible at a time:

onChangeVisibleRows={(visibleRows) => {
    const visibleRowNumbers = Object.keys(visibleRows.s1).map((row) => parseInt(row));
    if (visibleRowNumbers.length === 2) {
        // visible row is visibleRowNumbers[0]
    }
    if (visibleRowNumbers.length === 3) {
        // visible row is visibleRowNumbers[1]
    }
}

Caveat being that it doesn't perfectly map to the row that is most visible is considered visible. However, in using it, it makes sense while scrolling. In my particular application, there is a visible shift between the active and inactive rows so it helps the user understand whats happened.

doostin
  • 237
  • 2
  • 11
  • 2
    this solution will not work for Android as onChangeVisibleRows has not been implemented for Android yet. – Brackets Apr 12 '17 at 01:00
  • Annoyingly, it doesn't include the header in the callback, so you don't know if that is in view or not. Even though it scrolls just like an item at the top – conor909 Jan 16 '18 at 11:15
1

I don't have enough time to devise an accurate algorithm for your problem. But here is what you can do-

  1. Get scroll position. React native: get current scroll position of scrollview

  2. Get screen height. https://facebook.github.io/react-native/docs/dimensions.html#content

  3. Calculate approx. height of ListView child.

You can leverage these three things to find out how much space has been taken by a specific child.

By getting scroll position you can know how many pixels have you scrolled down. Divide that by height of your child, so that you can get how many children have been scrolled by the user.

(Scrolled height / Child height) = No. of children scrolled. 

And finally, onChangeVisibleRows will tell you which children are visible. Good luck!

Community
  • 1
  • 1
Mihir
  • 3,812
  • 3
  • 25
  • 29
  • Thanks for the response. I actually ended up going about it in another way(see my [answer](http://stackoverflow.com/a/36365410/2411446)) to avoid using onScroll. I have found that onScroll for uses like this can kill performance depending on how often you have to trigger the onScroll event. – doostin Apr 01 '16 at 20:36
  • @Mihir, is there anyway to compute the height of each child/row? what if each child/row height is dynamic, no fixed size? Thank you. – vvavepacket Jul 07 '17 at 13:47