I have FrameLayout
encapsulating two ImageView
s. Here is what I want:
Move the entire layout as and when touched and dragged by the user but when there is a click, it should be handled by the individual ImageView
s(through their respective View.OnClickListener()
)
Current behavior: Currently, when I try to drag the view group, it jumps randomly once(per drag event) and then starts to move with the finger. So, it's like you are moving your finger outside the view group and it's moving.
Secondly, there are no click events being routed to the child ImageView
s
What I have tried:
I have tried extending the FrameLayout
that is encapsulating the ImageView
s:
public class ChatHeadFrameLayout extends FrameLayout {
/**
* Store the initial touch down x coordinate
*/
private float initialTouchX;
/**
* Store the initial touch down y coordinate
*/
private float initialTouchY;
public ChatHeadFrameLayout(@NonNull Context context) {
super(context);
}
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(21)
public ChatHeadFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// If the event is a move, the ViewGroup needs to handle it and return
// the indication here
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Will be called in case we decide to intercept the event
// Handle the view move-with-touch behavior here
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
int Xdiff = (int) (event.getRawX() - initialTouchX);
int Ydiff = (int) (event.getRawY() - initialTouchY);
//The check for Xdiff <10 && YDiff< 10 because sometime elements moves a little while clicking.
//So that is click event.
if (Xdiff < 10 && Ydiff < 10) {
return false;
}
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view.
setX(event.getRawX() - initialTouchX);
setY(event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
invalidate();
return true;
}
return false;
}
}
So, what is wrong with this code?