Search code examples
android-arrayadapterandroid-tvvertical-scroll

How to implement a large single list efficiently in android TV using leanback library


I want to build a single list of very large number of UI elements (1000s) in Android TV using leanback library. I am currently extending VerticalGridFragment and using ArrayObjectAdapter. I want to start with binding (say) 100 elements and then bind next 100 elements when user reaches scrolling to end of the list. I don't see a way to implement this behavior.

VerticalGridFragment provides two listeners: OnItemViewClickedListener and OnItemViewSelectedListener. It seems very expensive to keep listening to every item being selected before making a query for next 100-elements.

Any ideas? Thanks.


Solution

  • There are two approaches I can think of. The first is to check the selected element, as you suggested. This is similar to my answer to this SO post. The listener itself is not expensive and as long as you are doing lightweight checks in the listener, then it will have a negligible effect on performance. The downfall to this approach is that if you're on a touch screen device (running leanback), you won't be able to pick up on scroll position since scrolling alone doesn't trigger item selection.

    Option 1:

    final int FETCH_NEXT_THRESHOLD = 5; // or NUM_COLUMNS * 2 if it's a grid
    final ListRow listRow = (ListRow) row;
    final ArrayObjectAdapter currentRowAdapter = listRow.getAdapter();
    int selectedIndex = currentRowAdapter.indexOf(item);
    if (selectedIndex != -1 && (currentRowAdapter.size() - index < FETCH_NEXT_THRESHOLD) {
        // One of the last FETCH_NEXT_THRESHOLD items was selected.
        // Trigger next page fetch now.
    }
    

    Option 2:

    The other approach relies on the fact that VerticalGridView is backed by RecyclerView. You could use something similar to this class. This checks for the number of child elements and which element is currently in view. This has an even larger impact on performance since it gets hit more frequently (but still a very minor impact). You can achieve this by adding a ScrollListener to your VerticalGridFragment's VerticalGridView which you'd most likely have to do at the Presenter level.

    Conclusion:

    I would suggest Option 1 since it is easier to implement and will accommodate most use cases. But if you're concerned about touch screen devices running leanback, you may want to go with an approach similar to Option 2.