2012-07-21 38 views
1

我試圖做一個簡單的計數器,從5計數到1並在每秒鐘後更新視圖。我試過沒有處理程序,只是用一個簡單的循環,但它只是在等待或強制關閉後顯示給我1。我已經嘗試了runOnUIThread和線程,但我錯過了一些東西。使用處理程序更新TextView

這裏是我的代碼:

package com.ammad.test; 
import android.os.Bundle; 
import android.os.Handler; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.support.v4.app.NavUtils; 

public class Main extends Activity { 

    TextView tv; 
    Button b1; 
    Handler mHandler; 
    int i = 5; 
    private Runnable runnable; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tv = (TextView) findViewById(R.id.tvShow); 
     b1 = (Button) findViewById(R.id.bt1); 



     runnable = new Runnable() { 
      public void run() { 
       // do your stuff - don't create a new runnable here! 
       tv.setText(String.valueOf(i)); 
       i--; 
       mHandler.postDelayed(runnable, 500); 

      } 
     }; 
     b1.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       mHandler.post(runnable); 
       mHandler.removeCallbacks(runnable); 

      } 
     }); 

    } 

    public void doTheLoop() { 

     /* 
     * runOnUiThread(new Runnable() { 
     * 
     * public void run() { for (int i = 5; i >= 1; i--) { // TODO 
     * Auto-generated method stub tv.setText(Integer.toString(i)); for (int 
     * j = 0; j < 200000; j++) ; } } 
     * `enter code here` 
     * }); 
     */ 
     // mHandler.post(runnable); 
    } 
} 

回答

0

你在哪裏實例mHandler?我認爲代碼丟失了,否則這會失敗,並出現NullPointerException異常。這很重要,因爲如果您只是在onCreate中用no-arg構造函數實例化它,它將使用UI線程的消息隊列。

還有其他的問題:在你的Runnable.run方法中,你實際上並不檢查i是否小於零,所以它總是會自己調用postDelayed。此外,您正在從非UI線程更新UI(setText),這可能會導致未定義的行爲。

我認爲你的代碼比它需要的複雜一點。如果這個例子是愚蠢的,並隱藏你的實際意圖,這是一個例子可能太簡單了,但這裏的東西基本上工作,雖然你需要編輯它一點來編譯(catch InterruptedException等)

new Thread() { 
     public void run() { 
      while(i > 0) { 
       Thread.sleep(1000); 
       mTextView.post(new Runnable() { 
        public void run() { 
         mTextView.setText(Integer.toString(i--)); 
        } 
       }); 
      } 
     } 
    }.start(); 
+0

thans alot dude ...你是一個救星...我一直在嘗試做同樣的事情,但我認爲我錯過了這個mTextView.post ... thanx了.. – Ammad 2012-07-21 12:29:52