Android invalidate()不更新textView

时间:2016-11-13 02:28:31

标签: android refresh textview invalidation

我正在尝试在定时循环旁边进行textView更新。每次循环时我都尝试使它无效()。这似乎有效,但应用程序在计时器启动时崩溃。

这是循环:

private Timer timer;
private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        thangO += 10;
        textypoo.setText(Integer.toString(thangO));
        textypoo.invalidate();
    }
};

public void start() {
    if (timer != null) {
        return;
    }
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

这是onCreate我初始化一些东西:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Intent intent = getIntent();
    textypoo = (TextView)findViewById(R.id.textmcview);

}

这是2个onClick方法。每当我按下它时更新textView,另一个调用计时器:

 public void sendthestuff(View view) {
    setContentView(R.layout.activity_second);
    textypoo = (TextView) findViewById(R.id.textmcview);
    thangO++;
    message = Integer.toString(thangO);
    textypoo.setText(message);


}

public void bazinga(View view) {
    start();
}

1 个答案:

答案 0 :(得分:0)

替换:

private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        thangO += 10;
        textypoo.setText(Integer.toString(thangO));
        textypoo.invalidate();
    }
};

要:

private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                thangO += 10;
                textypoo.setText(Integer.toString(thangO));
                textypoo.invalidate();
            }
        });
    }
};