Gurjit
Gurjit

Reputation: 564

How to stop animation on clicking the layout in android?

I have the following piece of code...

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

    final ImageView i = (ImageView) findViewById(R.id.imageView1);
    i.setBackgroundResource(R.anim.animation);

    i.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AnimationDrawable anim = (AnimationDrawable) i.getBackground();
            anim.start(); 
        }
    });
}

I want to add another listener on the background/layout so that when someone clicks on the image, the animation gets started and when someone clicks on the background it stops looping.

Any help is appreciated.

Upvotes: 0

Views: 1558

Answers (1)

Mike Ortiz
Mike Ortiz

Reputation: 4041

Move your animation drawable to a class variable. Then, start and stop it from onClickListeners hooked up to the ImageView and the background.

AnimationDrawable anim;

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


    final ImageView i = (ImageView) findViewById(R.id.imageView1);
    i.setBackgroundResource(R.anim.animation); 
    anim = (AnimationDrawable) i.getBackground();
    i.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            anim.start(); 

        }
    });

    // Or whatever type of layout it is
    LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
    myLayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            anim.stop(); 

        }
    });

}

Upvotes: 1

Related Questions