问题
I would like to ask, if is there a better away to call a method multiple times giving a 5 sec delay between each call.
But I really want is to call the Toas() method about 7 times, and with my code below, it doesnt look right.
Thanks guys
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
CallMultipleToast();
........
private void CallMultipleToast(){
Runnable call_1 = new Runnable() {
@Override
public void run() {
Toast("Message one");
Runnable call_2 = new Runnable() {
@Override
public void run() {
Toast("Message two");
Runnable call_3 = new Runnable() {
@Override
public void run() {
Toast("Message three");
//CAN I ADD MORE
}
};//end call_3
new Handler().postDelayed(call_3, 5000);
}
};//end call_2
new Handler().postDelayed(call_2, 5000);
}
};//end call_1
new Handler().postDelayed(call_1, 5000);
}
private void Toast(String message){
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
回答1:
maybe you can do it like this :
private void CallMultipleToast(){
Thread t = new Thread(){
@Override
public void run(){
try {
for(i=0;i<7;i++){
Toast("Message "+(i+1));
sleep(5000);
}
} catch (InterruptedException ex) {
Log.i("error","thread");
}
}
};
t.start();
}
回答2:
Try this:
final int DELAY= 5000;
int count = 0;
String[] msgs = {"one", "two", "three", "four", "five"};
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (count < 5) {
Toast(msgs[count]);
handler.post(runnable);
}
count++;
}
};
handler.postDelayed(runnable, DELAY);
来源:https://stackoverflow.com/questions/26050410/android-how-to-call-a-method-multiple-times-with-a-delay-between-them