按下时突出显示 RecyclerView 中的项目

Highlight item in RecyclerView while Pressed

我似乎找不到更简单的方法来仅在按下时突出显示 RecyclerView 项目,但是虽然我想出的这段代码似乎工作正常,但它将删除突出显示(ACTION_CANCEL 发生)如果我移动 up/down(按下时)但如果我在按下时向右或向左移动它会保持突出显示(不调用 ACTION_CANCEL 事件)。谁能告诉我为什么,或者是否有更好的方法?

           itemView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent pEvent) {
                selected_position = getAdapterPosition();
                if(pEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    parent.setBackgroundColor(Color.RED);
                    txtName.setTextColor(Color.GREEN);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_UP) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                    parent.setBackgroundColor(Color.WHITE);
                    txtName.setTextColor(Color.BLACK);
                }
                else if(pEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    int x = (int)pEvent.getRawX();
                    int y = (int)pEvent.getRawY();
                    int[] coordinates = new int[2];
                    parent.getLocationInWindow(coordinates);
                    if(x < (coordinates[0]) || (x > (coordinates[0]) + parent.getWidth())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else if(y < (coordinates[1]) || (y > (coordinates[1]) + parent.getHeight())) {
                        parent.setBackgroundColor(Color.WHITE);
                        txtName.setTextColor(Color.BLACK);
                    }
                    else {
                        parent.setBackgroundColor(Color.RED);
                        txtName.setTextColor(Color.GREEN);
                    }
                }
                return false;
            }
        });

在你的回收视图 item.xml 的根布局中,你可以写 android:foreground="?attr/selectableItemBackground"。当点击发生时,这将突出显示回收站视图项目。

例如,假设这是您的回收站视图项目布局:

 <androidx.constraintlayout.widget.ConstraintLayout

    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground">

     ...

</androidx.constraintlayout.widget.ConstraintLayout>`