当前位置: 代码迷 >> java >> Android:按钮淡出问题
  详细解决方案

Android:按钮淡出问题

热度:32   发布时间:2023-08-02 11:13:15.0

我创建了一个按钮,该按钮在被触摸时会淡入,而在没有触摸时会淡出。 我能够通过在Java中使用setAlpha来实现这一点。 代码和问题如下所示:

    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;
        }
    });

我遇到的问题是,每当释放按钮时,alpha便会设置为0,然后animationFadeOut才能完全播放,因此按钮不会退回。

如果我删除该行:

buttonPressed.getBackground().setAlpha(0);

然后将播放animationFadeOut但它将立即返回setAlpha(255)

当用户停止触摸按钮时,如何才能使animationFadeOut完全播放并使其按钮alpha为0

我认为使用setInterpolator()进行fadeIn和fadeOut动画可以解决您的问题。 例如:Animation animationFadeIn = new AlphaAnimation(0,1); animationFadeIn.setInterpolator(new DecelerateInterpolator()); animationFadeIn.setDuration(1000);

Animation animationFadeOut = new AlphaAnimation(1, 0);
animationFadeOut.setInterpolator(new AccelerateInterpolator());
animationFadeOut.setDuration(1000);

我从他的解决方案链接,你可以知道更多关于AccelerateInterpolator 。

目前无法测试。 但是似乎很有希望。 希望这可以帮助!

最好不要手动设置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;
  }
  相关解决方案