gpt4 book ai didi

java - 只有创建 View 层次结构的原始线程才能触摸它的 View ?

转载 作者:行者123 更新时间:2023-12-02 09:43:57 25 4
gpt4 key购买 nike

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

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

最佳答案

这是因为您尝试在不在 UI 线程中时触摸 View 。

快速修复如下所示:

之前的代码

score.setText(scorenewe.toString());

之后的代码:

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

这样你就可以告诉 Android 框架在主 UI 线程中运行这行代码,你可以在其中触摸你想要的任何 View 。 read this

关于java - 只有创建 View 层次结构的原始线程才能触摸它的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com