In Facebook, if you touch an item in your activity feed, it instantly darkens to show that your finger is on it. If you then use your finger to scroll the feed, the viewholder becomes white again.
You could also hold onto an item in your recyclerview and the viewholder will be darken. If you lift your finger, you have 'clicked' the item and Facebook shows you more information about what you have clicked.
This seems like quite an easy thing to implement but I have been struggling with it.
I think Facebook used the onTouchListener to implement the effect ...
I wrote the code below but it seems to darken the itemView of my recyclerview with an orange tint but when i drag or lift up my finger, the orange does not become the transparent color as I want it to be.
Also because the recyclerview is 'recycling' / reusing its view, if I touch the first item in the list and scroll, one of the items coming up from the bottom of the recyclerview will also get the orange tint as the view that has now moved out of sight (the first view that I clicked) has now been reused for the view at the bottom.
This is my code:
((ProfileFeedViewHolder) holder).itemView.setOnTouchListener(new View.OnTouchListener() {
public final static int FINGER_RELEASED = 0;
public final static int FINGER_TOUCHED = 1;
public final static int FINGER_DRAGGING = 2;
public final static int FINGER_UNDEFINED = 3;
private int fingerState = FINGER_RELEASED;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.e("motionEvent", "motion "+motionEvent.getAction());
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (fingerState == FINGER_RELEASED) fingerState = FINGER_TOUCHED;
else fingerState = FINGER_UNDEFINED;
view.setBackgroundColor(ContextCompat.getColor(context, R.color.deep_orange_500));
break;
case MotionEvent.ACTION_UP:
if(fingerState != FINGER_DRAGGING) {
fingerState = FINGER_RELEASED;
view.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
// Your onClick codes
}
else if (fingerState == FINGER_DRAGGING) fingerState = FINGER_RELEASED;
else fingerState = FINGER_UNDEFINED;
view.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
break;
case MotionEvent.ACTION_MOVE:
if (fingerState == FINGER_TOUCHED || fingerState == FINGER_DRAGGING) {
fingerState = FINGER_DRAGGING;
view.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
}
else fingerState = FINGER_UNDEFINED;
break;
default:
fingerState = FINGER_UNDEFINED;
view.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
}
return false;
}
});
How do I implement this simple effect that seems to be very popular on most apps nowadays?