Android: click / touch event not working after canvas translation

I have a FrameLayout that contains multiple ImageViews. In the main action, I record touch events to move my FrameLayout and images inside with my finger (drag and drop).

To do this, I call canvas.translate (x, y) inside the onDraw framelayout, which is called invalidate () in the activity touch event handler.

Everything works like a charm, except that after the translation I can’t click on my ImageView. In fact, the click listener of each image is still in its original location before translation.

I read that I need to manually update the layout of each image after the translation, but how to do it? If I changed the translation field, the images will go two more times ...

I would really appreciate any help with this.

Greetings.

Here is the Layout frame, where I translate the canvas in the onDraw () method (ImageViews are added to this FrameLayout in my main activity).

public class TopView extends FrameLayout {

public float mPosX = 0;
public float mPosY = 0;

public TopView(Context context)
{
    super(context);
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(1920, 3200, Gravity.CENTER);
    this.setLayoutParams(lp);
    setWillNotDraw(false);
}

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.translate(this.mPosX, this.mPosY);

}

}
+1
source share
1 answer

You can use setPadding (this.mPosX, this.mPosY, 0,0) in the constructor. It should work.

+1
source

Source: https://habr.com/ru/post/1541282/


All Articles