android – 应用程序崩溃与“从错误的线程异常”

前端之家收集整理的这篇文章主要介绍了android – 应用程序崩溃与“从错误的线程异常”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的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);

解决方法

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

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

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

    @Override
    public void run() {
              timerDisplayPanel.setText("Time =" + timerInt + "Sec");
            }
    });
        }
    },1000);
原文链接:https://www.f2er.com/android/312677.html

猜你在找的Android相关文章