Java 我希望一个图像淡出,另一个淡入时,它被点击,然后反过来
下面的代码应该使两个Java 我希望一个图像淡出,另一个淡入时,它被点击,然后反过来,java,android,if-statement,animation,Java,Android,If Statement,Animation,下面的代码应该使两个图像视图淡入淡出,一个需要淡入淡出,具体取决于计数器的值。出于某种原因,当我运行代码时,我会得到以下日志输出: I/Info: One I/Info Counter:: 1 I/Info: One I/Info Counter:: 1 ... 它从不显示: I/Info: Two I/Info Counter:: 0 有人能解释为什么会这样吗 代码如下: public void fade(View view) { int counter = 0; Imag
图像视图淡入淡出,一个需要淡入淡出,具体取决于计数器的值。出于某种原因,当我运行代码时,我会得到以下日志输出:
I/Info: One
I/Info Counter:: 1
I/Info: One
I/Info Counter:: 1
...
它从不显示:
I/Info: Two
I/Info Counter:: 0
有人能解释为什么会这样吗
代码如下:
public void fade(View view) {
int counter = 0;
ImageView bale = (ImageView) findViewById(R.id.bale);
ImageView pogba = (ImageView) findViewById(R.id.pogba);
if (counter == 0) {
bale.animate().alpha(0f).setDuration(2000);
pogba.animate().alpha(1f).setDuration(2000);
Log.i("Info", "One");
counter = 1;
} else if (counter == 1){
pogba.animate().alpha(1f).setDuration(2000);
bale.animate().alpha(0f).setDuration(2000);
Log.i("Info", "Two");
counter = 0;
}
Log.i("Info Counter: ", String.valueOf(counter));
}
您正在犯一个逻辑错误,代码在语法上没有任何错误。计数器的范围就是您遇到问题的地方计数器是一个局部变量,它只存在于淡入(…)
方法中。每次调用fade()
时,都会重新创建计数器
,并将其初始化为0
。这意味着,即使在if语句中将其设置为1
,下次调用fade()
时,它仍将是0
。您要么需要将其设置为类变量,要么使用下面描述的交替方法
非If语句交替方法:
您不需要if语句,只需获取pogba
和bale
的alpha,然后在设置其alpha时使用1f-pogba.getAlpha()
和1f-bale.getAlpha()
(使用返回其alpha的任何方法)。使用此方法将在1
和0
之间交替使用
因此,您的淡入淡出(查看)
方法将类似于以下内容:
public void fade(View view) {
ImageView bale = (ImageView) findViewById(R.id.bale);
ImageView pogba = (ImageView) findViewById(R.id.pogba);
// I'm not familiar with the method to get the alpha
// so it might not be getAlpha()
bale.animate().alpha(1f - bale.getAlpha()).setDuration(2000);
pogba.animate().alpha(1f - pogba.getAlpha()).setDuration(2000);
}
当然,您需要在代码的其他地方(可能是构造函数)执行以下操作
bale.setAlpha(1f); // I'm not familiar with the method to set the alpha
pogba.setAlpha(0f); // it might be setAlpha(), but I'm not sure
请不要截取代码或错误消息的屏幕抓图。这使得其他有这个问题的人很难找到这个问题。请编辑您的问题,将其包含在问题主体中。我尝试了您建议的代码,现在一切正常。谢谢!