[英]Android: button fade out issue
I have created a button that fades in when it is being touched and fades out when it isn't. 我创建了一个按钮,该按钮在被触摸时会淡入,而在没有触摸时会淡出。 I was able to achieve this by using setAlpha in java.
我能够通过在Java中使用setAlpha来实现这一点。 The code and the problem is shown below:
代码和问题如下所示:
buttonPressed.getBackground().setAlpha(0);
buttonPressed.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
buttonPressed.getBackground().setAlpha(255);
buttonPressed.startAnimation(animationFadeIn);
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
buttonPressed.startAnimation(animationFadeOut);
return true;
}
return false;
}
});
The issue I have is whenever I release the button, the alpha is set to 0 before animationFadeOut
is able to fully play, so the button does not fade back. 我遇到的问题是,每当释放按钮时,alpha便会设置为0,然后
animationFadeOut
才能完全播放,因此按钮不会退回。
If I remove the line: 如果我删除该行:
buttonPressed.getBackground().setAlpha(0);
then animationFadeOut
will play but it will immediately go back to setAlpha(255)
. 然后将播放
animationFadeOut
但它将立即返回setAlpha(255)
。
How can I get animationFadeOut
to play fully and have the button alpha be 0
when the user stops touching the button? 当用户停止触摸按钮时,如何才能使
animationFadeOut
完全播放并使其按钮alpha为0
?
I think using setInterpolator() for fadeIn and fadeOut animation solves your problem. 我认为使用setInterpolator()进行fadeIn和fadeOut动画可以解决您的问题。 eg: Animation animationFadeIn = new AlphaAnimation(0, 1);
例如:Animation animationFadeIn = new AlphaAnimation(0,1); animationFadeIn.setInterpolator(new DecelerateInterpolator());
animationFadeIn.setInterpolator(new DecelerateInterpolator()); animationFadeIn.setDuration(1000);
animationFadeIn.setDuration(1000);
Animation animationFadeOut = new AlphaAnimation(1, 0);
animationFadeOut.setInterpolator(new AccelerateInterpolator());
animationFadeOut.setDuration(1000);
I got his solution from this link and you can know more about AccelerateInterpolator here . 我从他的解决方案这个链接,你可以知道更多关于AccelerateInterpolator 这里 。
Currently unable to test it. 目前无法测试。 But seems to be promising.
但是似乎很有希望。 Hope this helps!
希望这可以帮助!
Better not to set the alpha manually, use animators to set the alpha 最好不要手动设置Alpha,而使用动画师设置Alpha
// Define the animators
Animation fadeInAnimation = new AlphaAnimation(0.0f, 1.0f);
Animation fadeOutAnimation = new AlphaAnimation(1.0f, 0.0f);
// Duration of animation
fadeInAnimation.setDuration(1000);
fadeOutAnimation.setDuration(1000);
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
buttonPressed.startAnimation(fadeInAnimation);
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
buttonPressed.startAnimation(fadeOutAnimation);
return true;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.