通过单击一个按钮启动循环和停止代码

ncecgwcz  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(293)

我想做一个简单的按钮,它将开始循环一个功能,每一段时间,我可以设置。但它不仅会启动循环,而且如果我再按一下按钮,它也会停止循环。不管怎样,我可以用一个按钮来实现这一点吗?

gab6jxml

gab6jxml1#

是的,举个简单的例子。
首先,创建两个常量值和一个示例变量:

//indicate whether or not the loop is running
    private boolean isRunning = false;

    //used for handler to send empty msg
    private final static int MSG_LOOP = 1;
    private final static long LOOP_INTERVAL = 5000;

然后创建一个 Handler 示例来处理循环逻辑:

Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_LOOP:
                    doStuff();
                    break;
            }
        }
    };

    private void doStuff() {
        //after what you want to do is done, send another MSG_LOOP msg with delay
        handler.sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
    }

最后:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRunning) {
                    //cancel if any in the message queue
                    handler.removeMessages(MSG_LOOP);
                } else {
                    //if you do not want to start the loop immediately, then use: "sendEmptyMessageDelayed"
                    handler.sendEmptyMessage(MSG_LOOP);
                }

            }
        });
vof42yt1

vof42yt12#

我会这样做的

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private View.OnClickListener runOnClickListener;
    private View.OnClickListener stopOnClickListener;

    void init() {
        Handler handler = new Handler();
        int duration = 5000;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                foo();
                handler.postDelayed(this, duration);
            }
        };

        runOnClickListener = view -> {
            runnable.run();
            btn.setOnClickListener(stopOnClickListener);
        };

        stopOnClickListener = view -> {
            handler.removeCallbacks(runnable);
            btn.setOnClickListener(runOnClickListener);
        };

       btn.setOnClickListener(runOnClickListener);
    }

    void foo() {
        Log.i("foo", "foo");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = findViewById(R.id.btn);

        init();
    }
}

相关问题