gpt4 book ai didi

Android - 每 5 秒循环部分代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:30 26 4
gpt4 key购买 nike

我想在按下“开始”按钮时开始每 5 秒重复两行代码,并在按下“停止”按钮时结束它。我正在尝试使用 TimerTask 和 Handles,但无法弄清楚如何。

public class MainActivity extends Activity {




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


//final int i;
final TextView textView = (TextView) findViewById(R.id.textView);
final Button START_STOP = (Button) findViewById(R.id.START_STOP);
final ImageView random_note = (ImageView) findViewById(R.id.random_note);
final int min = 0;
final int max = 2;
final Integer[] image = { R.drawable.a0, R.drawable.a1,R.drawable.a2 };



START_STOP.setTag(1);
START_STOP.setText("START");


START_STOP.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
int status = (Integer) v.getTag();
if (status ==1) {
textView.setText("Hello");
START_STOP.setText("STOP");
v.setTag(0);

final Random random = new Random();

//************************************************************
// I would like to loop next 2 lines of code every 5 seconds.//

int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);

//************************************************************
}

else
{
textView.setText("Bye");
START_STOP.setText("Let's PLAY!");
v.setTag(1);
}


}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

最佳答案

在其他答案之一中使用 CountDownTimer 是一种方法。另一种方法是使用 Handler 和 postDelayed方法:

private boolean started = false;
private Handler handler = new Handler();

private Runnable runnable = new Runnable() {
@Override
public void run() {
final Random random = new Random();
int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);
if(started) {
start();
}
}
};

public void stop() {
started = false;
handler.removeCallbacks(runnable);
}

public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}

这是一个使用 Timer 和 TimerTask 的例子:

private Timer timer;
private TimerTask timerTask = new TimerTask() {

@Override
public void run() {
final Random random = new Random();
int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);
}
};

public void start() {
if(timer != null) {
return;
}
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

public void stop() {
timer.cancel();
timer = null;
}

关于Android - 每 5 秒循环部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21726055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com