Java – Android image fade animation

Android image fade animation… here is a solution to the problem.

Android image fade animation

When I run this code, it does nothing, I’m sure this event is called when I touch the button. But it does not change the opacity of the imageView.

View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        ObjectAnimator fadeAltAnim = ObjectAnimator.ofFloat(R.id.imgTest, "alpha", 0.2f);
        fadeAltAnim.start();
    }
};

findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);

Is there something wrong with my code?

Solution

Try this code, which uses ViewPropertyAnimator:

View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener()   {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

view.animate().alpha(0.2f).setDuration(1000);
    }
};

It’s always good to set the duration so that the animation knows how long it should run.

Edit: If you are using onTouchListener, you may want to attach it to a MotionEvent, for example:

View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener()   {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if(motionEvent == MotionEvent.ACTION_DOWN)
        view.animate().alpha(0.2f).setDuration(1000);
    }
}; 

Edit 2:

If you want to use

a Button, it’s better to use OnClickListener instead of onTouchListener, and if you want to attach an image, you must launch it (e.g. in ImageView):

Button button = (Button) findViewById(R.id.your_button);
ImageView imageView = (ImageView) findViewById(R.id.imgTest);

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

imageView.animate().alpha(0.2f).setDuration(1000);

}
};

Related Problems and Solutions