应用与崩溃“叫是非线程异常”

问题描述 投票:12回答:1

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

logcat的:

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);
android handler timertask
1个回答
33
投票
Only the UI thread that created a view hierarchy can touch its views.

您正在试图改变非UI线程的UI元素的文本,所以它给exception.Use 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);
© www.soinside.com 2019 - 2024. All rights reserved.