14

我在我的方法中添加了这部分代码,onCreate()它使我的应用程序崩溃。需要帮忙。

日志猫:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread 
that created a view hierarchy can touch its views.

代码:

final TextView timerDisplayPanel = (TextView) findViewById(R.id.textView2);

    Timer t = new Timer();
    t.schedule(new TimerTask(){
        public void run(){
            timerInt++;
            Log.d("timer", "timer");
            timerDisplayPanel.setText("Time ="+ timerInt +"Sec");
        }
    },10, 1000);
4

1 回答 1

37
Only the UI thread that created a view hierarchy can touch its views.

您正在尝试更改非 UI 线程中 UI 元素的文本,因此它给出了异常。使用runOnUiThread

 Timer t = new Timer();
 t.schedule(new TimerTask() {
 public void run() {
        timerInt++;
        Log.d("timer", "timer");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timerDisplayPanel.setText("Time =" + timerInt + "Sec");
            }
        });

    }
}, 10, 1000);
于 2012-06-16T11:00:46.407 回答