vxh.viet
4/29/2016 - 7:48 AM

add Fade animation to ImageView

add Fade animation to ImageView

Source: StackOverflow

Question: How to fade in and out an ImageView on touch event?

Answer:

yourImgView.setOnTouchListener(new MyOnTouchListener());

private class MyOnTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    
                    //hide wheel background
                    Animation fadeOut = UIUtil.getFadeOut();
                    fadeOut.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {}

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            yourImgView.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {}
                    });
                    yourImgView.startAnimation(fadeOut);                   

                    break;

                case MotionEvent.ACTION_MOVE:
                    
                    break;

                case MotionEvent.ACTION_UP:                    

                    Animation fadeIn = UIUtil.getFadeIn();
                    fadeIn.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            mVideoActivity.getWheelBackground().setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {}

                        @Override
                        public void onAnimationRepeat(Animation animation) {}
                    });
                    yourImgView.startAnimation(fadeIn);
                   
                    break;
            }
            return true;
        }
    }

Then in UIUtil

    public static Animation getFadeIn(){
        Animation fadeIn = new AlphaAnimation(0, 1);
        fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
        fadeIn.setDuration(500);
        return fadeIn;
    }

    public static Animation getFadeOut(){
        Animation fadeOut = new AlphaAnimation(1, 0);
        fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
        fadeOut.setStartOffset(20);
        fadeOut.setDuration(500);
        return fadeOut;
    }