应用程序崩溃,显示"Called From Wrong Thread Exception"

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

我不知道如何使用处理程序。我在某个地方读到需要使用处理程序对象。 - jeet.chanchawat
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接