首页 > 解决方案 > How to start and stop an animation of a rotating ImageView with button

问题描述

I want to press play button and then spin a disc: imageRound. At pause I want to stop the disc at current position, and then on play continue from current position.

I am trying to get each time the angle with imageRound.getRotation() but it goes back to 0 each time. My code is as follows:

playButton.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch(event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            if (playShow) {
                                playButton.setBackgroundResource(R.drawable.play_pressed);
                            } else {
                                playButton.setBackgroundResource(R.drawable.pause_pressed);}
                            return true; //handle the touch event
                        case MotionEvent.ACTION_UP:
                            if (playShow) {
                                playButton.setBackgroundResource(R.drawable.pause_default);
                                RotateAnimation rotate = new RotateAnimation(imageRound.getRotation(), 360, Animation.RELATIVE_TO_SELF,
                                        0.5f,  Animation.RELATIVE_TO_SELF, 0.5f);
                                rotate.setDuration(5000);
                                imageRound.startAnimation(rotate);
                                playShow=false;
                            } else {
                                playButton.setBackgroundResource(R.drawable.play_default);
                                imageRound.setRotation(imageRound.getRotation()); //(Not working) Set angle and stop animation
                                imageRound.clearAnimation();
                                playShow=true;
                            }
                            return true; // handle the touch event
                    }
                    return false;
                }
            });

标签: javaandroidanimationrotation

解决方案


imageRound.getRotation()每次都返回0吗?RotateAnimation 不会改变视图的属性。使用ObjectAnimator.ofFloat(imageview ,"rotation", 0f, 360f)这直接改变视图的旋转属性。


推荐阅读