运行 循环中的一个方法

running a method in a loop

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

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

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

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

好的,所以我现在对 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);
}