动画触摸时启动,UnTouched时停止

时间:2013-09-14 16:23:27

标签: java android animation

所以我的问题是如何制作动画在触摸时开始,一旦它没有触摸它会播放另一个动画.. (对不起我的英文..)

main.java:

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView is = (ImageView) findViewById(R.id.img1);
        is.setBackgroundResource(R.animator.animup);
        final AnimationDrawable animup = (AnimationDrawable) is.getBackground();
        final ImageView iv = (ImageView) findViewById(R.id.img1);
        iv.setBackgroundResource(R.animator.anim);  
        final AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
        is.setOnTouchListener(new OnTouchListener() {



                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_DOWN) { 
                        anim.setVisible(true, true);
                        anim.start();

                        //perform your animation when button is touched and held
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        anim.setVisible(true, true);
                        animup.start();

                        //perform your animation when button is released
                    }
                    return false;




                }
            });

    };

    ;
  }

+另一个问题...... 的 EDITED

1 个答案:

答案 0 :(得分:1)

我认为link会帮助你。

修改

要实施触控和发布,您必须使用onTouchListener而不是onClickListener

以下是代码 -

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //perform your animation when button is touched and held
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          //perform your animation when button is released
        }
    }
};

修改2

else if块中,您未将anim的可见性设置为false。我觉得这就是问题所在。以此形式重写您的代码 -

button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            anim.setVisible(true,true);
            anim.start();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
         anim.stop(); //perform your animation when button is released
         animup.setVisible(true,true);
         animup.start();
       }
    }
};