Pausing with handler and postDelayed in android

后端 未结 2 1089
傲寒
傲寒 2021-01-02 04:57

I\'m very new to android programming so please forgive my noobie-ness. I\'m trying to create a very simple activity that will have one TextView in the middle of the Layout a

相关标签:
2条回答
  • 2021-01-02 05:16

    This is because your loop is setting all your handlers to run after 7 seconds not 7 seconds after each other but but after 7 seconds from now. You can either add in the postDelayed method or use the postAtTime method in handler .

    Also, you don't need to do this in a thread, you can get rid of that altogether.

    0 讨论(0)
  • 2021-01-02 05:30

    postDelayed is non blocking, meaning it would add it to a queue of I'll do this later. So what you are probably seeing is all text updates happening together at the 7th second. I say this because you are postDelaying from the onCreate method when in reality you probably want to do it from onResume or even onPostResume.

    Also there is no reason to create a thread to add runnables to the post queue. Your code should look more like this: (Note the time to delay multiplier)

    @Override
    protected void onResume() {
        super.onResume();
        for (int count = 0; count < arraylength; count++){
            handler.postDelayed(new Runnable(){
                @Override
                public void run() {
                    mytexts.setText(myarray[count]);
                }
            }, 7000 * (count + 1));
        }
    }
    
    0 讨论(0)
提交回复
热议问题