循环运行方法

时间:2018-11-03 18:54:23

标签: android loops methods infinite-loop

我正在Android Studio中编写我的第一个应用程序。我有一种方法可以在其中一项活动中移动图片,而我只是希望它能够持续工作。我唯一知道的方法是通过创建一个按钮并单击它来运行它,但是我找不到没有按钮就可以运行它的任何解决方案

这就是我想要运行的方法:

    public void ruchIceberg(){
    iceberg = (ImageView)findViewById(R.id.imageView);

    if(iceberg.getX()<=-iceberg.getWidth()/2){
        setIceberg(iceberg);
    }
    setIceberg(iceberg,60);
}

1 个答案:

答案 0 :(得分:0)

好的,所以我现在对Android有点生锈,但是... 我通常使用的方法是像这样使用Handler.postDelayed()

  1. 计划要启动任务的运行时间

  2. Runnable的正文中,重新安排另一次跑步(如果需要)。

示例代码:

//In your Activity.java
private Handler timerHandler = new Handler();
private boolean shouldRun = true;
private Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
        if (shouldRun) {
            /* Put your code here */
            //run again after 200 milliseconds (1/5 sec)
            timerHandler.postDelayed(this, 200);
        }
    }
};

//In this example, the timer is started when the activity is loaded, but this need not to be the case
@Override
public void onResume() {
    super.onResume();
    /* ... */
    timerHandler.postDelayed(timerRunnable, 0);
}

//Stop task when the user quits the activity
@Override
public void onPause() {
    super.onPause();
    /* ... */
    shouldRun = false;
    timerHandler.removeCallbacksAndMessages(timerRunnable);
}