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



我似乎找不到一种更简单的方法来只在按下时突出显示RecyclerView项目,但尽管我想出的代码似乎工作正常,但如果我向上/向下移动(按下时(,它会删除突出显示(ACTION_CANCEL发生(,但如果在按下时向右或向左移动,它会保持突出显示(不调用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>`

最新更新