Android simple textview text change with timer

2020-03-31 04:05发布

I am new to android and just starting through some tutorial videos. My requirement is initially i need to show the textview text to "red" and after 5-10 sec, need to change it to "hello red".

I have tried two method alternatively. In first method its giving me exception while in second method its starting the application after given delay and directly show me the "hello red" text. I might be missing some basic concepts here. Could you pls help me ?

       TextView myText;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myText = (TextView)findViewById(R.id.displayTv);
    // ------ first method start ---------
    Thread timer = new Thread(){
        public void run(){
            try{
                sleep(6000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
                myText.setText("Hello red");
            }
        }
    };
    timer.start();
    // ------ first method end ---------
    // ------ second method start ---------
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    myText.setText("Hello red");
    // ------ second method end ---------
}

}

2条回答
萌系小妹纸
2楼-- · 2020-03-31 04:42

Try to Use Handler,

Handler h=new Handler();
h.postDelayed(new Runnable(){
public void run(){
//change your text here
}
}, time_delay);
查看更多
爷、活的狠高调
3楼-- · 2020-03-31 05:01
    _tv = (TextView) findViewById( R.id.textView1 );
     tv2 = (TextView) findViewById( R.id.textView2 );
    _tv.setText( "red" );
    _t = new Timer();

    _t.scheduleAtFixedRate( new TimerTask() {
            @Override
            public void run() {
                _count++;

                runOnUiThread(new Runnable() //run on ui thread
                 {
                  public void run() 
                  { 
                     tv2.setText(""+_count);
                     if(_count==5)
                     {
                    _tv.setText("hello red" );
                    _tv.setTextColor(Color.RED);
                     }
                 }
                 });
            }
        }, 1000, 1000 ); 
查看更多
登录 后发表回答