0
我有5 Buttons
。每個Button
的文本都設置爲list_of_letters
的一個隨機字母。此外,這些字母每5秒鐘一次顯示一次 - 這就是爲什麼我使用Handler
和Runnable
。並且每隔5秒鐘,將添加到Button
的那封信從list_of_letters
中刪除。處理程序暫停或停止操作
問題:當所有5個Buttons
包含一個字母時,Runnable
仍在運行並每5秒從list_of_letters
中刪除字母。有沒有辦法可以暫停Handler
或停止其動作,以便只在Button
不包含文字時纔會運行?
這裏是我的代碼:
for (int i = 0; i < 10; i++) {
Runnable x = new Runnable(){
@Override
public void run(){
random_counter = rand.nextInt(my_list_counter);
for(Button b:button_list) //contains the 5 buttons
if (b.getText().equals("")){ //if button is empty, add text to it
b.setText(list_of_letters.get(random_counter)); //sets text to random letter from List
break;
}
list_of_letters.remove(list_of_letters.get(random_counter)); //then removes that letter from the List
my_list_counter--;
}
};
Handler handler = new Handler();
handler.postAtTime(x, SystemClock.uptimeMillis() + i*5000); //a letter gets posted every 5 seconds
}
編輯:這裏是我當前的代碼。在handler.post(x)
有錯誤。該錯誤說:本地變量x
可能尚未初始化。你的代碼的
final Runnable x = new Runnable() {
@Override
public void run(){
if(my_list_counter <= 0)
return; // i'm guessing my_list_counter is the length of the array/list.
random_counter = rand.nextInt(my_list_counter);
for(Button b:button_list) //contains the 5 buttons
{
if (b.getText().equals("")) { //if button is empty, add text to it
b.setText(list_of_letters.get(random_counter)); //sets text to random letter from List
list_of_letters.remove(list_of_letters.get(random_counter)); //then removes that letter from the List
my_list_counter--;
Handler handler = new Handler();
handler.post(x);
// handler.postAtTime(x, SystemClock.uptimeMillis() + 5000); //a letter gets posted every 5 seconds
break;
}
}
}
};
我會嘗試這個,但這裏有一些錯誤:'我'沒有在handler.postAtTime中定義,x也不存在 – user2456977 2014-12-04 04:41:38
當我添加最終的Runnable x = new Runnable到你的答案時,我仍然得到一個錯誤在行:handler.postAtTime(x,SystemClock.uptimeMillis()+ i * 5000);它說局部變量x mat沒有被初始化。有任何想法嗎? – user2456977 2014-12-04 04:51:54
感謝您編輯@Happy Cupz Cupz,但仍然存在錯誤。我編輯我的帖子上面的問題。請讓我知道你是否可以幫忙。再次感謝 – user2456977 2014-12-04 05:15:10