Search code examples
androidandroid-layoutandroid-recyclerviewandroid-tvleanback

Android Leanback library HorizontalGridView scrollToPosition doesn't work


I'm implementing an Android TV app and I'm using HorizontalGridView from the Leanback library. I have a custom layout.

I have to scroll the HorizontalGridView to specific position, after activity is created, but unfortunately the scrollToPositio(position) method is not working on this layout at all. It just do nothing. I found, that when I specifically set the layout manager to LinearLayoutManager it works. But the problem is, that when I'm not using leanback default HorizontalGridView LayoutManager, there is a problem with focusing next items using D-pad.

Basically if I use normal RecyclerView, the control with D-pad is not working as expected, so I decided to go with leanback implementation, where this problem is solved, but so far I cannot make it work with scrollToPosition method.

Any ideas?

Snippet of my code:

Layout:

<android.support.v17.leanback.widget.HorizontalGridView
        android:id="@+id/photo_gallery_recycler"
        android:layout_width="match_parent"
        android:layout_height="@dimen/gallery_image_size"
        android:clipChildren="false"
        app:itemView="@{viewModel.photoItemView}"
        app:items="@{viewModel.photosUrl}"/>

Code [Kotlin]:

binding.photoGalleryRecycler.scrollToPosition(position)
binding.photoGalleryRecycler.getChildAt(position)?.requestFocus()

And I also tried some hacks like this:

// save default leanback layout manager    
var defaultLayoutManager = binding.photoGalleryRecycler.layoutManager
// set LinearLayoutManager
binding.photoGalleryRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
// scroll to position and request focus
binding.photoGalleryRecycler.scrollToPosition(position)
binding.photoGalleryRecycler.getChildAt(position)?.requestFocus()
// set default layout manager back to the view
binding.photoGalleryRecycler.layoutManager = defaultLayoutManager

Solution

  • you need to be using setSelectedPosition(position)

    If animation is required you can try setSelectedPositionSmooth(position)

    setSelectedPosition Developer docs.