Android Leanback 库 Horizo​​ntalGridView scrollToPosition 不起作用

Android Leanback library HorizontalGridView scrollToPosition doesn't work

我正在实施一个 Android 电视应用程序,并且我正在使用 Leanback library 中的 HorizontalGridView。我有一个自定义布局。

创建 activity 后,我必须将 HorizontalGridView 滚动到特定位置,但不幸的是 scrollToPositio(position) 方法根本不适用于此布局。它什么都不做。我发现,当我专门将 layout manager 设置为 LinearLayoutManager 时,它会起作用。但问题是,当我不使用 leanback 默认值 HorizontalGridView LayoutManager 时,使用方向键聚焦下一个项目时会出现问题。

基本上,如果我使用普通 RecyclerView,使用方向键的控件无法按预期工作,所以我决定使用 leanback 实现,解决了这个问题,但到目前为止我无法使用 scrollToPosition 方法使其工作。

有什么想法吗?

我的代码片段:

布局:

<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}"/>

代码 [Kotlin]:

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

我也尝试过一些这样的技巧:

// 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

您需要使用 setSelectedPosition(position)

如果需要动画可以试试setSelectedPositionSmooth(position)

setSelectedPosition Developer docs.