Using a timer to alter the alpha for object for a few seconds?

139 views Asked by At

I'm an android newbie so need the simplest code example here, I have a Layout where upon an OnClick, I want to set the alpha to 0.50 for 2 seconds before it navigates me to another page (kind of like a button shade effect).

LinearLayout ChangeThisLayoutAlpha = (LinearLayout) findViewById(R.id.ThisLayout);
ChangeThisLayoutAlpha.setAlpha((float) 0.50);

How do I use a timer or whatever to have a 2 second pause between (a) having it shaded for 2 seconds before the device navigates me to the other page (and changes the alpha back to 1.0)?

Thank you!

1

There are 1 answers

1
npace On BEST ANSWER

I'd say the easiest way is to use an ObjectAnimator, like in the tutorial here.

Your code would look something like this:

final LinearLayout ChangeThisLayoutAlpha= (LinearLayout) findViewById(R.id.ThisLayout); 
ObjectAnimator animator = ObjectAnimator.ofFloat(ChangeThisLayoutAlpha, "alpha", 1f, 0.5f);
animator.setDuration(2000);
animator.addListener(new AnimatorListenerAdapter() {
    public void onAnimationEnd(Animator animation) {
       ChangeThisLayoutAlpha.setAlpha(1f);
       // Do your transition to the next screen here
    }
})
animator.start();

Don't forget to check out the ObjectAnimator documentation for additional details!

Edit: As @njzk2 pointed out, a simpler approach would be to use the ViewPropertyAnimator, since you can chain the calls like in his comment. If you support API level 16 and above, you can use the withEndAction(Runnable r) method, otherwise you can use the addListener(AnimatorListener listener) like in the code snippet at the start of this post.