在 RecyclerView 视图上捕获 KeyEvent
Capture KeyEvent on RecyclerView Views
按照 this 博客上的说明 post 我可以在垂直列表适配器上跟踪所选项目,但我无法通过按某个键单击或长按任何项目。
我已经创建了这个方法
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;
}
}
拦截"confirm"按钮,但哪里是监听KeyEvents
的正确位置?如何区分点击和长按?
我编辑了 post 中的代码,添加了定期和长按按钮:
@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 (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
return tryMoveSelection(lm, 1);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
return tryMoveSelection(lm, -1);
} else if(KeyEventUtils.isConfirmButton(event)){
View view = mRecyclerView.findViewHolderForAdapterPosition(mSelectedItem).itemView;
if((event.getFlags() & KeyEvent.FLAG_LONG_PRESS)==KeyEvent.FLAG_LONG_PRESS) {
view.performLongClick();
}
else{
view.performClick();
}
return true;
}
}
return false;
}
});
}
现在可以正常使用了,不知道是不是最优雅的方式。
按照 this 博客上的说明 post 我可以在垂直列表适配器上跟踪所选项目,但我无法通过按某个键单击或长按任何项目。
我已经创建了这个方法
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;
}
}
拦截"confirm"按钮,但哪里是监听KeyEvents
的正确位置?如何区分点击和长按?
我编辑了 post 中的代码,添加了定期和长按按钮:
@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 (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
return tryMoveSelection(lm, 1);
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
return tryMoveSelection(lm, -1);
} else if(KeyEventUtils.isConfirmButton(event)){
View view = mRecyclerView.findViewHolderForAdapterPosition(mSelectedItem).itemView;
if((event.getFlags() & KeyEvent.FLAG_LONG_PRESS)==KeyEvent.FLAG_LONG_PRESS) {
view.performLongClick();
}
else{
view.performClick();
}
return true;
}
}
return false;
}
});
}
现在可以正常使用了,不知道是不是最优雅的方式。