我想将文本设置为25个按钮,但每个文本在5秒后都会出现。我尝试过使用很多不同的方法。我尝试使用Thread.sleep(5000),但我的程序崩溃。然后我试图创建一个Handler,但它崩溃了。有人可以告诉我为什么吗?或者是有另一种方式,我应该推迟文本:Android延迟文本
*注意:在我的代码中,我使用findViewById方法,但决定不要在这里发布它为了简单和重复的缘故 - 所以这不是问题。
public class Game extends Activity {
protected List<String> my_list = new ArrayList<String>();
protected String letters[];
protected List<Button> button_list = new ArrayList<Button>();
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10,
b11, b12, b13, b14, b15, b16, b17, b18, b19, b20,
b21, b22, b23, b24;
Random rand = new Random();
int random_counter;
int my_list_counter = 25;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
letters = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y"};
Button[] bttn_arr = new Button[] {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10,
b11, b12, b13, b14, b15, b16, b17, b18, b19, b20,
b21, b22, b23, b24};
my_list.addAll(Arrays.asList(letters));
button_list.addAll(Arrays.asList(bttn_arr));
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for (i=0; i<25; i++){
random_counter = rand.nextInt(my_list_counter);
button_list.get(i).setText(my_list.get(random_counter));
my_list.remove(my_list.get(random_counter));
my_list_counter--;
handler.postDelayed(this, 5000);
}
}
});
}
}
**从来没有**在UI线程中使用Thread.sleep。处理程序是要走的路。如果您的程序崩溃了,请查看您在控制台中获得的异常,可能是空指针异常或类似情况。顺便说一下,你同时安排了25个电话到同一个可运行的,要小心,这可能会成倍地增长 – rupps 2014-11-02 05:05:46
感谢您的建议。我仍然试图找出问题所在。我正在实施Kaylwin的答案,但似乎仍然存在一个错误,因为我在下面发布。稍稍改变Kaylwin的代码后,程序等待5秒钟,然后显示所有文本。它不会每隔5秒显示每个文本... – user2456977 2014-11-02 14:49:22