我使用ObjectAnimator制作了#34;心跳效果按钮"(连续闪烁),并且工作正常。
有4个按钮,名为btn1RT,btn2LT,btn3LB和btn4RB。如果其中一个按钮开始闪烁,则其他按钮将消失。
问题:我重构了这段代码,它不再有用了。我无法停止按钮闪烁,所以我的所有按钮都闪烁。我想知道为什么这些按钮无法停止。
我认为将ObjectAnimator作为参数传递是个问题,但是没有任何线索。
任何帮助将不胜感激。
之前:
private void start1HeartBeat() {
oa1 = ObjectAnimator.ofFloat(btn1RT, "alpha", 1, 0);
oa1.setDuration(HEARTBEAT_RUN_DURATION);
oa1.setRepeatCount(ValueAnimator.INFINITE);
oa1.setRepeatMode(ValueAnimator.REVERSE);
oa1.start();
if (oa2.isRunning()) {
oa2.end();
oa2 = ObjectAnimator.ofFloat(btn2LT, "alpha", 0.5f, 0);
oa2.setDuration(HEARTBEAT_STOP_DURATION);
oa2.setRepeatCount(0);
oa2.setRepeatMode(ValueAnimator.RESTART);
oa2.start();
}
if (oa3.isRunning()) {
oa3.end();
oa3 = ObjectAnimator.ofFloat(btn3LB, "alpha", 0.5f, 0);
oa3.setDuration(HEARTBEAT_STOP_DURATION);
oa3.setRepeatCount(0);
oa3.setRepeatMode(ValueAnimator.RESTART);
oa3.start();
}
if (oa4.isRunning()) {
oa4.end();
oa4 = ObjectAnimator.ofFloat(btn4RB, "alpha", 0.5f, 0);
oa4.setDuration(HEARTBEAT_STOP_DURATION);
oa4.setRepeatCount(0);
oa4.setRepeatMode(ValueAnimator.RESTART);
oa4.start();
}
}
}
重构后:这不起作用。
private void start1HeartBeat() {
startHeartBeat(oa1, btn1RT);
stopHeartBeat(oa2, btn2LT);
stopHeartBeat(oa3, btn3LB);
stopHeartBeat(oa4, btn4RB);
}
private synchronized void startHeartBeat(ObjectAnimator oa, Object btn) {
oa = ObjectAnimator.ofFloat(btn, "alpha", 1, 0);
oa.setDuration(HEARTBEAT_RUN_DURATION);
oa.setRepeatCount(ValueAnimator.INFINITE);
oa.setRepeatMode(ValueAnimator.REVERSE);
oa.start();
}
private synchronized void stopHeartBeat(ObjectAnimator oa, Object btn) {
if (oa.isRunning()) {
oa.end();
oa = ObjectAnimator.ofFloat(btn, "alpha", 0.5f, 0);
oa.setDuration(HEARTBEAT_STOP_DURATION);
oa.setRepeatCount(0);
oa.setRepeatMode(ValueAnimator.RESTART);
oa.start();
}
}
答案 0 :(得分:1)
要理解这个问题,我们应该清楚传递值和传递引用之间的区别。对于Java的情况,this post更好地阐明了这一概念。
简而言之,在Java中,引用本身是按值传递的。正如我们在传值中所知,方法内部的变化不会反映在外部。因此,在方法中更改传递的引用不会反映在外部。
有了这些知识,正确重构代码的方法之一如下
private void start1HeartBeat() {
oa1 = startHeartBeat(oa1, btn1RT);
oa2 = stopHeartBeat(oa2, btn2LT);
oa3 = stopHeartBeat(oa3, btn3LB);
oa4 = stopHeartBeat(oa4, btn4RB);
}
private synchronized ObjectAnimator startHeartBeat(ObjectAnimator oa, Object btn) {
oa = ObjectAnimator.ofFloat(btn, "alpha", 1, 0);
oa.setDuration(HEARTBEAT_RUN_DURATION);
oa.setRepeatCount(ValueAnimator.INFINITE);
oa.setRepeatMode(ValueAnimator.REVERSE);
oa.start();
return oa;
}
private synchronized ObjectAnimator stopHeartBeat(ObjectAnimator oa, Object btn) {
if (oa.isRunning()) {
oa.end();
oa = ObjectAnimator.ofFloat(btn, "alpha", 0.5f, 0);
oa.setDuration(HEARTBEAT_STOP_DURATION);
oa.setRepeatCount(0);
oa.setRepeatMode(ValueAnimator.RESTART);
oa.start();
}
return oa;
}
我刚刚提到了一种可能的重构方法。由于核心问题已得到澄清,因此您需要以适当的方式进行重构。