0

I'm working on a simple card game. I have a card stack which is simply an imageview. On touch I create a custom card object (view). To move the cards around I have overridden the onTouchEvent method in the Card object.

The question is, how can I move the card immediately when tapping on the stack to create it? At the moment I first need to tap (create card), lift the finger and tap again to move the card around.

I've already seen How to programmatically trigger the touch event in android? but this just triggers a touch event for a moment I guess.

Activity

public void createCard(View v) {
    if (mCardCounter < 4) {
        Card card = new Card(this);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
        layoutParams.setMargins(30, 30, 0, 0);
        card.setLayoutParams(layoutParams);
        mRootFrameLayout.addView(card);
        mCardCounter++;
    }

Card

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            dX = this.getX() - event.getRawX();
            dY = this.getY() - event.getRawY();
            break;
        case MotionEvent.ACTION_MOVE:
            this.animate()
                    .x(event.getRawX() + dX)
                    .y(event.getRawY() + dY)
                    .setDuration(0)
                    .start();
            }
            break;
        case MotionEvent.ACTION_UP:
            break;
    }
    return true;
}
Zuop
  • 584
  • 5
  • 7
  • 21

1 Answers1

0

You could try something like this.

Create a boolean value that has a scope for the entire Activity.

boolean isActionDown = false;

Then inside the onTouchEvent method

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_MOVE:
            if(!isActionDown){
                isActionDown = true;
                dX = this.getX() - event.getRawX();
                dY = this.getY() - event.getRawY();
            }
            else{
                this.animate()
                    .x(event.getRawX() + dX)
                    .y(event.getRawY() + dY)
                    .setDuration(0)
                    .start();
                }
            }
            break;
        case MotionEvent.ACTION_UP:
            isActionDown = false;
            break;
    }
    return true;
}
Barns
  • 4,850
  • 3
  • 17
  • 31
  • could you please explain your approach a little more? The problem is that the Card object doesn't receive any touchEvents at all because it was only created and added on the screen. First touch events fire when lifting the finger and touch again – Zuop Nov 23 '17 at 20:22