我成功地实现了一个抽象的适配器类,能够跟踪所选项目而不失去项目焦点。可以在这里找到一个示例项目,适配器类的具体实现如下:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
/**
* Created by vektor on 31/05/16.
*/
public abstract class InputTrackingRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH>{
private Context mContext;
private int mSelectedItem = 0;
private RecyclerView mRecyclerView;
public InputTrackingRecyclerViewAdapter(Context context){
mContext = context;
}
@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = 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 (isConfirmButton(event)) {
if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) == KeyEvent.FLAG_LONG_PRESS) {
mRecyclerView.findViewHolderForAdapterPosition(mSelectedItem).itemView.performLongClick();
} else {
event.startTracking();
}
return true;
}
else {
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
return tryMoveSelection(lm, 1);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
return tryMoveSelection(lm, -1);
}
}
}
else if(event.getAction() == KeyEvent.ACTION_UP && isConfirmButton(event)
&& ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != KeyEvent.FLAG_LONG_PRESS)){
mRecyclerView.findViewHolderForAdapterPosition(mSelectedItem).itemView.performClick();
return true;
}
return false;
}
});
}
private boolean tryMoveSelection(RecyclerView.LayoutManager lm, int direction) {
int nextSelectItem = mSelectedItem + direction;
// If still within valid bounds, move the selection, notify to redraw, and scroll
if (nextSelectItem >= 0 && nextSelectItem < getItemCount()) {
notifyItemChanged(mSelectedItem);
mSelectedItem = nextSelectItem;
notifyItemChanged(mSelectedItem);
//lm.scrollToPosition(mSelectedItem);
mRecyclerView.smoothScrollToPosition(mSelectedItem);
return true;
}
return false;
}
public Context getContext(){ return mContext; }
public int getSelectedItem() { return mSelectedItem; }
public void setSelectedItem(int selectedItem) { mSelectedItem = selectedItem; }
public RecyclerView getRecyclerView() { return mRecyclerView; }
@Override
public void onBindViewHolder(VH holder, int position) {
onBindViewHolder(holder, position);
}
public static boolean isConfirmButton(KeyEvent event){
switch (event.getKeyCode()){
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_BUTTON_A:
return true;
default:
return false;
}
}
}
RecyclerView
更新,而不是每个按键事件都更新一次。话虽如此,在垂直滚动列表下方放置一个可聚焦视图本身就不是一个好的键盘用户体验。您将在编写Android TV应用程序(或其Google TV前身,Fire TV等)的相关报道中看到有关这类事情的讨论。 - CommonsWare