Question

I'm trying to create an android application that when I touch anywhere on the screen does the following things:

  1. A new ImageView has to appear at the center of the screen(at least for this example lets say that the picture in the image view is an arrow);
  2. The has arrow to point towards the direction where I touched the screen.
  3. The arrow has to translate(using an animation) from the center of the screen to where the screen was touched.

Since I'm kinda new in Android I don't know exactly what is the best way to do it, so I came up with the following, not working, solution:

happyrelativelayout.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() ==MotionEvent.ACTION_DOWN){
                ImageView arrow = new ImageView(ctx);
                arrow.setImageResource(R.drawable.arrow);
                arrow.setX(centerx);
                arrow.setY(centery);
                float angle = -(float) Math.toDegrees(Math.atan2(centerx - event.getX(), centery - event.getY()));
                arrow.setRotation(angle);
                happyrelativelayout.addView(arrow);
                arrowanimation = new TranslateAnimation(0, event.getX() - centerx, 0, event.getY() - centery);
                arrowanimation.setFillAfter(true);
                arrowanimation.setDuration(1000);
                arrow.startanimation(arrowanimation);
            }
       }
}

With this solution everything seems to go how it has to go except the animation. Even if the arrow moves to the touched point, there is no animation, the arrow just blinks from the center to the touched point. I'm I missing something important?

Was it helpful?

Solution

The code looks right to be, but I have never used TranslateAnimation()

Personally I use the ObjectAnimator class, this is normally because I want to use NineOldAndroids to support older versions.

This is how it might look using ObjectAnimator.

final ObjectAnimator translateX = ObjectAnimator.ofFloat(arrow, "translationX", centerX, event.getX());
translateX.setDuration(1000);

final ObjectAnimator translateY = ObjectAnimator.ofFloat(arrow, "translationY", centerY, event.getY());
translateY.setDuration(1000);

final AnimatorSet moveAnimation = new AnimatorSet();
moveAnimation.playTogether(translateX, translateY);
moveAnimation.start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top