简体   繁体   English

按钮点击后如何等待执行操作?

[英]How to wait to perform an action after button click?

As a beginner in Android programming, I don't really master the use of the threads and the Handler() function. 作为Android编程的初学者,我并不真正掌握线程和Handler()函数的使用。 After clicking on a button, I'd like to call a first method startProjection() then wait a few seconds before call a second method stopProjection (). 点击一个按钮后,我想调用第一个方法startProjection()然后等几秒钟再调用第二个方法stopProjection ()。

By reading some topics about the question, I built this code, able to perform the first call but not the second : 通过阅读有关该问题的一些主题,我构建了这段代码,能够执行第一个调用而不是第二个调用:

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

    // some code

    // start projection
    Button startButton = (Button) findViewById(R.id.startButton);
    startButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startProjection();

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    stopProjection();
                }
            }, 7000);
        }
    });

The Build Gradle works correctly but when I finally click on the Button nothing happens. Build Gradle正常工作,但是当我最终点击Button时没有任何反应。 It seems that the handler doesn't work correctly. 似乎处理程序无法正常工作。 Is there anyway to perform these actions in the same onClick() method ? 无论如何在同一个onClick()方法中执行这些操作?

EDIT : Previously the two methods were called separately buy using two buttons (and it works !), but I really want to use a single button. 编辑:以前这两个方法分别叫做使用两个按钮购买(它工作!),但我真的想使用一个按钮。

I just want to check if you have any specific reason to have stopProjection() function in a seperate thread. 我只想检查你是否有任何特定的理由在一个单独的线程中使用stopProjection()函数。 May be the following might work fine : 可能以下可能正常工作:

startProjection();
Thread.sleep(7000);
stopProjection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM