Capture KeyEvent on RecyclerView Views

半世苍凉 提交于 2019-12-01 11:26:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!