预期结果
按钮可以像切换开关一样起作用,这样, (1)第一次点击按钮向右移动 (2)第二次点击按钮向左移动 (3)第三次点击按钮向右移动 等等......
问题
标志变量flagToggleButton
不能在按钮的OnClickListener事件监听器回调函数中使用。
Main.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;
}
}
});
}
}
最佳答案
使其成为类的成员变量。换句话说,在 onCreate()
public class Main extends Activity {
boolean flagToggleButton = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
// rest of your code
关于java - 如何在 Android 应用程序的事件监听器回调中使用标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419209/