Search code examples
javaandroidimagebuttonfadeout

android – show a button for a limited time


I am making an app where an ImageButton is shown and fades until it disappears if the user doesn't touch it for too long.
I tried many different solutions (animation, wait(), etc.) but nothing did what I tried to...
It should work like a Toast, just show up for 3 seconds and then fade out (in the end of the process the visibility should be GONE.


Solution

  • Use a timer and alpha

    long duration = 5000 // 5 seconds
    long tick = 100 // 0.1 seconds;
    
    new CountDownTimer(duration, tick) {
    
         public void onTick(long millisUntilFinished) {
             mImageButton.setAlpha(millisUntilFinished / (float)duration)
         }
    
         public void onFinish() {
             mImageButton.setVisibility(View.GONE);
             mImageButton.setAlpha(1); // incase you want to show the button again
         }
    }.start();
    

    setAlpha() - Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.