Android Textview未更新

时间:2012-11-27 23:23:12

标签: android multithreading timer textview

大家。 我正在尝试为Android制作基本的大亨游戏 我试图用计时器每隔5秒增加一次文本视图的值, 但是textview没有更新。 到目前为止,这是我的代码:

public class Town extends Activity implements OnClickListener {
Timer timer;
TimerTask task;
TextView goldTV;
TextView woodTV;
TextView foodTV;
TextView stoneTV;
TextView cashTV;
int gold = 20;
int wood = 20;
int food = 20;
int stone = 20;
int cash = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_town);
    goldTV = (TextView) findViewById(R.id.textView1);
    woodTV = (TextView) findViewById(R.id.TextView01);
    foodTV = (TextView) findViewById(R.id.TextView02);
    stoneTV = (TextView) findViewById(R.id.TextView03);
    cashTV = (TextView) findViewById(R.id.TextView04);
    timer = new Timer();
    task = new TimerTask() {

        @Override
        public void run() {
            gold++;
            goldTV.setText(gold);
            try {
                this.wait(2000);
            }
            catch (InterruptedException e){
            }
        }

    };
}
@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub

}

}

3 个答案:

答案 0 :(得分:4)

使用run()方法

@Override
public void run() {
          gold++;
          goldTV.setText(gold);

          try {
                this.wait(2000);
          }
          catch (InterruptedException e){

          }
}

您正在呼叫setText(int resId)而不是setText(CharSequence c);

要显示实际的整数gold,请将其从int转换为String

String goldStr = String.valueOf(gold);

goldTV.setText(goldStr);

答案 1 :(得分:3)

您的问题是您正在更改UI线程以外的其他内容。更好的是在UI线程上运行它。另外,您应该将您的号码转换为字符串,否则Android会认为您正在寻找资源ID。把它们放在一起,然后......

task = new TimerTask() {

    @Override
    public void run() {
        gold++;
        runOnUiThread(new Runnable(){
           public void run(){
            goldTV.setText(""+gold);
           }
        });
        try {
            this.wait(5000);
        }
        catch (InterruptedException e){
        }
    }

};

甚至更好,您可以使用处理程序,如下所示:

Handler handler = new Handler();
Runnable task=new Runnable(){
   public void run(){
      handler.postDelayed(this,5000);
      goldTV.setText(""+gold);
   }
});
handler.postDelayed(task,5000);

答案 2 :(得分:1)

TimerTask应该与Timer对象一起使用。在您的代码中,您永远不会运行任务。

修改 试试这个:

goldTV.postDelayed(new Runnable() {

            @Override
            public void run() {
                gold++;
                goldTV.setText(gold+"");
                goldTV.postDelayed(this,2000);
            }
        }, 2000);