预期结果
按钮的作用类似于切换,这样,(1) 第一次单击它,按钮向右移动 (2) 第二次单击它,按钮向左移动 (3) 第三次单击它,按钮向右移动等等....
问题
flag 变量flagToggleButton
不能在按钮的 OnClickListener 事件监听回调函数中使用。
主.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button b = (Button) findViewById(R.id.button1);
boolean flagToggleButton = false;
b.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View arg0) {
if (flagToggleButton == false) {
Animation anim = AnimationUtils.loadAnimation(Main.this,
R.anim.animation_move_right);
b.startAnimation(anim);
flagToggleButton = true;
}
else {
Animation anim = AnimationUtils.loadAnimation(Main.this,
R.anim.animation_move_left);
b.startAnimation(anim);
flagToggleButton = false;
}
}
});
}
}