0

预期结果

按钮的作用类似于切换,这样,(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;
                }
            }
        });
    }
}
4

2 回答 2

2

让它成为你的类的成员变量。换句话说,在外面定义它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
于 2013-07-02T06:53:35.517 回答
1

全局放

布尔标志切换按钮 = 假;

b.setOnClickListener(new OnClickListener () {
            @Override
            public void onClick(View arg0) {
                if (!(flagToggleButton)) {
                    // do stuff..
                    flagToggleButton = true;
                }
                else {
                    // do stuff..
                    flagToggleButton = false;
                }
            }
        });
于 2013-07-02T06:54:27.863 回答