gpt4 book ai didi

android - 如何在另一个线程中设置 TextView 的文本

转载 作者:IT老高 更新时间:2023-10-28 23:26:37 27 4
gpt4 key购买 nike

我正在尝试在另一个线程中设置文本,即子线程。但是对于以下代码,它给出了错误

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

 

 

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.img);
pb = (ProgressBar)findViewById(R.id.pb);
this.tv = (TextView)findViewById(R.id.perc);
tv.setText("30 %");
pb.setProgress(30);
pb.setMax(100);
}

public void set(int p)
{
tv.setText(p + " %");
}

protected void onStart()
{
super.onStart();
pb.setProgress(20);

Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
try {
int i = pb.getProgress();
while(i <100)
{
while(pb.getProgress()<100)
{
pb.incrementProgressBy(5);
Thread.sleep(1000);
}
i+=10;
pb.setProgress(i);
Thread.interrupted();
set(i);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
t.start();
}

最佳答案

您需要对该 TextView 的引用,然后执行:

textView.post(new Runnable() {
public void run() {
textView.setText(yourText);
}
});

在 Kotlin 中:

val textView: TextView = findViewById(R.id.textView)
textView.post(Runnable { textView.setText(yourText) })

关于android - 如何在另一个线程中设置 TextView 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9884246/

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