Android延迟文字

时间:2014-11-02 04:49:17

标签: android handler delay

我想将文本设置为25个按钮,但每个文本在5秒后出现。我尝试过使用大量不同的方法。我尝试使用Thread.sleep(5000),但我的程序崩溃了。然后我试图创建一个处理程序,但它崩溃了。有人可以告诉我为什么吗?还是有另一种方法我推迟文本:

*注意:在我的代码中,我使用了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);
            }
        }
    });
}   

}

2 个答案:

答案 0 :(得分:1)

请尝试改编:

for (int i = 0; i < 20; i++) {
       final String message = "Hello" + i;
        Runnable x = new Runnable(){
            @Override
            public void run(){
                Log.i("Hello", message);

            }
        };

       Handler handler = new Handler();
       //Run the code in runnable x at increasing time intervals of 5 seconds
       handler.postAtTime(x, SystemClock.uptimeMillis() + i*5000);

    }

}


此代码将每5秒打印出“hello”+ i(例如hello1,然后是hello2,然后是hello3等)。如果您将代码调整为此,它将每5秒运行一次。在前面的例子中,处理程序一次发布并运行所有runnables,现在它立即发布所有runnables,除非每个runnables的开始时间增加5秒(参见handler.postAtTime(...))。希望这有帮助!

答案 1 :(得分:0)

像这样使用处理程序

for(int i=0;i<25;i++){
final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

              //do something here

            }
        }, 5000);
 }