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

jexiocij  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(329)

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

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

我不能改变 score. score.setText(scorenewe.toString()); 第45行

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

svgewumm1#

这是因为您试图在不在ui线程中的情况下触摸视图。
快速修复如下所示:
前面的代码

score.setText(scorenewe.toString());

后面的代码:

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

这样你就可以告诉android框架在主ui线程中运行这行代码,在那里你可以触摸任何你想要的视图

idfiyjo8

idfiyjo82#

解决方案:

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是一个活动函数。

相关问题