Android simple textview text change with timer

2020-03-31 04:35发布

问题:

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 ---------
}

}

回答1:

Try to Use Handler,

Handler h=new Handler();
h.postDelayed(new Runnable(){
public void run(){
//change your text here
}
}, time_delay);


回答2:

    _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 );