其他分享
首页 > 其他分享> > android-在RecyclerView视图上捕获KeyEvent

android-在RecyclerView视图上捕获KeyEvent

作者:互联网

遵循this博客文章上的指示,我可以在垂直列表适配器上跟踪选定的项目,但是无法通过按某些键单击或长按任何项目.

我已经创建了这种方法

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;
    }
}

拦截“确认”按钮,但是侦听KeyEvent的正确位置在哪里?如何区分点击和longclick?

解决方法:

我通过添加常规和长按按钮来编辑帖子中的代码:

@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;
        }
    });
}

现在它可以正常工作,我不知道这是否是最优雅的方法.

标签:android-keypad,recycler-adapter,android,android-recyclerview
来源: https://codeday.me/bug/20191009/1882315.html