我想用文本视图显示信件。在一段时间间隔后,该字母应显示在textview中。
我用了以下代码…

String a="Apple";
String b="";
.......
.......


public void run() {

    for (int i = 0; i < 5; i++) {
        b=b+""+a.charAt(i);
        mTextView.setText(b); //Problem here
        Log.d("Letters",""+b);
            try {
                  sleep(2000);
           } catch (InterruptedException e) {}
    }

日志分类结果:
android.view.viewroot$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能访问其视图。
有什么解决办法吗?

最佳答案

不能从其他线程更改UI控件。以下一种方式更新代码:

public void run() {

    for (int i = 0; i < 5; i++) {
        b=b+""+a.charAt(i);

        //one of the ways to update UI controls from non-UI thread.
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                mTextView.setText(b); //no problems here :)
            }
        });

        Log.d("Letters",""+b);
            try {
                  sleep(2000);
           } catch (InterruptedException e) {}
    }
}

08-05 02:40
查看更多