Search code examples
androidobjectanimator

In android How to use a variable(without making it final) from outer class in onAnimationEnd() method in AnimatorListener


I am trying to change the image of an ImageButton when the translate animation of another ImageView has ended. I have an AnimatorListener for the animation and would like to pass the ImageButton value in the onAnimationEnd method so that I know which ImageButton to change(some computation take place in the code to decide which Imagebutton to change). My code is as follows. Please help me!!!

//animation of an imageview
ObjectAnimator move =ObjectAnimator.ofFloat(myAnimation1,"translationX",20);

//calculating which image to change to for the ImageButton
int id2 = this.getResources().getIdentifier("r" + a[m], "drawable", this.getBaseContext().getPackageName());

//adding animtor listener

move.addListener(new Animator.AnimatorListener(ImageButton,id2) {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        // TODO Auto-generated method stub

                        ImageButton.setImageResource(id2); //Not able to use ImageButton and id2...says it has to be final but I don't want it to be final

                        ImageButton.setClickable(true);

                    }});

Solution

  • Just create another final variable?

    int id2 = this.getResources().getIdentifier("r" + a[m], "drawable", this.getBaseContext().getPackageName());
    
    final int idFinal = id2;
    
    //adding animtor listener
    
    move.addListener(new Animator.AnimatorListener(ImageButton,id2) {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            // TODO Auto-generated method stub
    
                            ImageButton.setImageResource(idFinal); //Not able to use ImageButton and id2...says it has to be final but I don't want it to be final
    
                            ImageButton.setClickable(true);
    
                        }});