简单实现textview文本每隔两秒就改变一次


//这个方法可以实现文本每隔两秒就改变一次,
    public void textTask(){
         final android.os.Handler handler=new android.os.Handler(){
            @Override
            public void handleMessage(Message msg) {
                if ((msg.arg1)%2==0){
                    tv.setText("22222");
                }else {
                    tv.setText("11111");
                }
                super.handleMessage(msg);
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                int count=1;
                while (flag){//这是个死循环,需要在activity消失时,把flag设为false,结束循环
                    Message msg=new Message();
                    msg.arg1=count;
                    handler.sendMessage(msg);
                    count++;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onStop() {
        flag=false;
        super.onStop();
    }

  

posted @ 2018-05-21 11:46  咸鱼公子  Views(587)  Comments(0Edit  收藏  举报