【问题标题】:running a method in a loop在循环中运行方法
【发布时间】:2018-11-03 18:54:23
【问题描述】:

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

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

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

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

【问题讨论】:

  • 所以您希望它在活动开始后立即运行?
  • 是的,我希望它在活动开始时运行
  • 所以你可以在你的activity的onResume方法中调用这个方法。这样,一旦你的布局被创建,这个方法就会运行

标签: android loops methods infinite-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 2011-12-10
    • 2015-12-03
    • 2017-08-22
    • 1970-01-01
    • 2018-08-11
    • 2013-01-12
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多