Creating animation on ImageView while changing image resource

后端 未结 4 1357
情深已故
情深已故 2020-12-01 02:23

I have only one ImageView in my layout and I am changing its resource when a gasture event detected. I just want to show an animation while changing resource of

4条回答
  •  鱼传尺愫
    2020-12-01 02:56

    Here's an example using ImageSwitcher like @Konstantin Burov suggested:

    Add this ImageSwitcher element to your xml layout:

    
    
    

    Create in and out animations in res/anim/:

    Out animation:

    //left_to_right_out.xml
    
    
        
    
    

    And in animation:

    //left_to_right_in.xml
    
    
        
    
    

    Initialize them in your code:

            Animation in  = AnimationUtils.loadAnimation(this, R.anim.left_to_right_in);
            Animation out = AnimationUtils.loadAnimation(this, R.anim.left_to_right_out);
    

    Initialize your ImageSwitcher:

    private ImageSwitcher imageSwitcher;
    imageSwitcher = (ImageSwitcher)findViewById(R.id.slide_trans_imageswitcher);
    

    Attach the animations to it:

    imageSwitcher.setInAnimation(in);
    imageSwitcher.setOutAnimation(out);
    

    Now everytime you set an image resource for imageSwitcher, it will switch in a slide animation.


    For example we can change the image every X seconds:

    private int animationCounter = 1;
    private Handler imageSwitcherHandler;
    imageSwitcherHandler = new Handler(Looper.getMainLooper());
    imageSwitcherHandler.post(new Runnable() {
        @Override
        public void run() {
            switch (animationCounter++) {
                case 1:
                    imageSwitcher.setImageResource(R.drawable.image1);
                    break;
                case 2:
                    imageSwitcher.setImageResource(R.drawable.image2);
                    break;
                case 3:
                    imageSwitcher.setImageResource(R.drawable.image3);
                    break;
            }
            animationCounter %= 4;
            if(animationCounter == 0 ) animationCounter = 1;
    
            imageSwitcherHandler.postDelayed(this, 3000);
        }
    });
    

提交回复
热议问题