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

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

在创建活动之后,我必须将HorizontalGridView滚动到特定位置,但不幸的是, scrollToPositio(position)方法根本无法在此布局上工作。 它什么都不做。 我发现,当我专门设置layout manager LinearLayoutManager它的作品。 但问题是,当我不使用leanback默认的HorizontalGridView LayoutManager ,使用D-pad聚焦下一个项目时出现问题。

基本上,如果我使用普通的RecyclerView ,带有D-pad的控件不能按预期工作,所以我决定采用leanback实现,这个问题已经解决了,但是到目前为止我还是无法使用scrollToPosition方法。

有任何想法吗?

我的代码片段:

布局:

  

代码[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)

如果需要animation,你可以尝试setSelectedPositionSmooth(position)

setSelectedPosition开发人员文档。