Android TV 中的 RecyclerView 项目焦点
Posted
技术标签:
【中文标题】Android TV 中的 RecyclerView 项目焦点【英文标题】:RecyclerView item focus in Android TV 【发布时间】:2020-10-11 05:54:30 【问题描述】:如何在 android tv 应用中关注 recyclerview 项目?
我在 Horizontal Recyclerview 的右侧使用带有 Imageview 的 recyclerview。
【问题讨论】:
在定义 ImageView 的 xml 中添加这两个属性 "android:focusable=true","android:focusableInTouchMode=true" 【参考方案1】:public abstract class TrackSelectionAdapter<VH extends TrackSelectionAdapter.ViewHolder> extends RecyclerView.Adapter<VH>
// Start with first item selected
private int selectedItem = 0;
@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView)
super.onAttachedToRecyclerView(recyclerView);
// Handle key up and key down and attempt to move selection
recyclerView.setOnKeyListener(new View.OnKeyListener()
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
// Return false if scrolled to the bounds and allow focus to move off the list
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
return tryMoveSelection(lm, 1);
else if (keyCode == KeyEvent.KEYCODE_DPAD_UP)
return tryMoveSelection(lm, -1);
return false;
);
private boolean tryMoveSelection(RecyclerView.LayoutManager lm, int direction)
int nextSelectItem = selectedItem + direction;
// If still within valid bounds, move the selection, notify to redraw, and scroll
if (nextSelectItem >= 0 && nextSelectItem < getItemCount())
notifyItemChanged(selectedItem);
selectedItem = nextSelectItem;
notifyItemChanged(selectedItem);
lm.scrollToPosition(selectedItem);
return true;
return false;
@Override
public void onBindViewHolder(VH viewHolder, int position)
// Set selected state; use a state list drawable to style the view
viewHolder.itemView.setSelected(selectedItem == position);
public class ViewHolder extends RecyclerView.ViewHolder
public ViewHolder(View itemView)
super(itemView);
// Handle item click and set the selection
itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
// Redraw the old selection and the new
notifyItemChanged(selectedItem);
selectedItem = mRecyclerView.getChildPosition(v);
notifyItemChanged(selectedItem);
);
【讨论】:
以上是关于Android TV 中的 RecyclerView 项目焦点的主要内容,如果未能解决你的问题,请参考以下文章
Android TV 开发-->Leanback 中的 BrowseSupportFragment
Android TV:从 ListRowPresenter 中的项目中删除阴影
Android TV(leanback)中的持久标头片段(禁用动画)