如何在我的主要活动中循环一段代码?

Igo*_*dev 2 java random android loops

我正在使用 Android Studio,我想每半秒循环一次

"Random rand = new Random(); 
int value = rand.nextInt(10);"
Run Code Online (Sandbox Code Playgroud)

无论如何,感谢您抽出宝贵的时间,如果您能提供帮助,那就太好了。:)

此致,
伊戈尔

编辑
感谢大家的友善和有用的答案。我会在尝试完每个答案后立即选择最佳答案。(现在我的电脑还没有)但是再次感谢大家。编辑
对于任何有类似问题的人,我让它工作。这是最终的代码。包 sarju7.click;

import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.Random;


public class MainActivity extends ActionBarActivity {

    Random rand = new Random();
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Runnable r = new Runnable() {
            public void run() {
                int value = rand.nextInt(10);
                TextView t1 = (TextView) findViewById(R.id.clicker);
                t1.setText(Integer.toString(value));
                handler.postDelayed(this, 400);
            }
        };
        handler.postDelayed(r, 400);
    }

    }
Run Code Online (Sandbox Code Playgroud)

再次感谢大家。你们是最棒的。我喜欢所有的堆栈溢出!

Com*_*are 5

使用postDelayed()。例如,此活动Toast每五秒显示一次:

/***
  Copyright (c) 2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
 */

package com.commonsware.android.post;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class PostDelayedDemo extends Activity implements Runnable {
  private static final int PERIOD=5000;
  private View root=null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    root=findViewById(android.R.id.content);
  }

  @Override
  public void onResume() {
    super.onResume();

    run();
  }

  @Override
  public void onPause() {
    root.removeCallbacks(this);

    super.onPause();
  }

  @Override
  public void run() {
    Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
         .show();
    root.postDelayed(this, PERIOD);
  }
}
Run Code Online (Sandbox Code Playgroud)

run()的方法Runnable是进行工作并安排Runnable在所需的延迟时间后再次运行。只需调用即可removeCallbacks()结束循环。您可以调用postDelayed()任何小部件;就我而言,我使用的是框架提供的FrameLayoutandroid.R.id.content因为此活动没有其他 UI。