问题
Following the directions on this blog post I am able to track the selected item on a vertical list Adapter, but I cannot click or long click any item by pressing some key.
I've created this method
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;
}
}
to intercept "confirm" buttons, but where's the right place to listen for KeyEvents
? How to make a distinction between click and longclick?
回答1:
I have edited the code from the post, by adding regular and long button presses:
@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;
}
});
}
Now it works properly, I don't know if it's the most elegant way.
来源:https://stackoverflow.com/questions/32921705/capture-keyevent-on-recyclerview-views