I can't seem to find a simpler way to only highlight a RecyclerView item when pressed but while this code I have come up with seems to work ok it will remove the highlight (ACTION_CANCEL occurs) if I move up/down (while pressed) but it stays highlighted if I move right or left while pressed (No ACTION_CANCEL event is called). Can anyone tell me why or if there is better way of doing this please?
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;
}
});