只有创建视图层次结构的原始线程才能触及其视图?

时间:2017-10-31 17:37:20

标签: java android timer

我无法解决此错误: android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

TextView score;
private SharedPreferences speicher;
private SharedPreferences.Editor editor;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    score = (TextView) findViewById(R.id.score);
    speicher = getApplicationContext().getSharedPreferences("Daten", 0);
    editor = speicher.edit();
    loadfile("score" , score);

    new Timer().scheduleAtFixedRate(new TimerTask() {
        public void run() {
            Integer scorealt = Integer.parseInt(speicher.getString("score", null));
            Integer scorenewe = scorealt + Integer.parseInt(speicher.getString("anz", null));
            score.setText(scorenewe.toString());
            savefile("score", scorenewe.toString());
        }
    }, 0, 2000);
}

我无法在第45行更改score. score.setText(scorenewe.toString());

android.view.ViewRootImpl$CalledFromWrongThreadException: 
    Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7769)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1332)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5446)
at android.view.View.invalidateInternal(View.java:14750)
at android.view.View.invalidate(View.java:14714)
at android.view.View.invalidate(View.java:14698)
at android.widget.TextView.checkForRelayout(TextView.java:8535)
at android.widget.TextView.setText(TextView.java:5076)
at android.widget.TextView.setText(TextView.java:4901)
at android.widget.TextView.setText(TextView.java:4876)
at de.yt.tutorial.Home$1.run(Home.java:45)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

2 个答案:

答案 0 :(得分:4)

解决方案:

new Timer().scheduleAtFixedRate(new TimerTask() {
        public void run() {
                RunOnUiThread(new Runnable() {
      @Override
      public void run() {
        Integer scorealt = Integer.parseInt(speicher.getString("score", null));
            Integer scorenewe = scorealt + Integer.parseInt(speicher.getString("anz", null));
            score.setText(scorenewe.toString());
            savefile("score", scorenewe.toString());
        }
    }
    }, 0, 2000);

函数RunOnUIThread是一个Activity函数。

答案 1 :(得分:2)

这是因为你没有在UI线程中试图触摸视图。

快速修复如下所示:

之前的

代码

score.setText(scorenewe.toString());

之后的代码:

new Handler(Looper.getMainLooper()).post(new Runnable(){
    @Override
    public void run() {
        score.setText(scorenewe.toString());
    }
});

这样你就可以告诉Android框架在主UI线程中运行这行代码,在那里你可以触摸你想要的任何视图P.S. read this