gpt4 book ai didi

android - 使用线程显示进度条

转载 作者:搜寻专家 更新时间:2023-11-01 08:09:56 26 4
gpt4 key购买 nike

我正在尝试使用线程来显示进度条。我承认我对线程没有那么多的概念。

这是代码

public class Progress extends Activity {

static String[] display;
private static final int Progress = 0;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);

mProgress = (ProgressBar) findViewById(R.id.progressBar);

// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();

// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}

private int doWork() {
display = new Logic().finaldata();
// TODO Auto-generated method stub
return 100;
}
}).start();
}
}

在运行时,logcat 消息是

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我在这里做错了什么?

最佳答案

所以你的问题会在别处。我用 Handler 试过你的例子,它对我有用。

package com.sajmon.threadsDemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ThreadsDemoActivity extends Activity {

ProgressBar bar;
TextView label;
Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progBar);

new Thread(new Runnable() {

int i = 0;
int progressStatus = 0;

public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Update the progress bar
handler.post(new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i++;
}
});
}
}
private int doWork() {

return i * 3;
}

}).start();

}
}

和 XML:

<ProgressBar 
android:id="@+id/progBar" style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

所以看看这个并用类似的方式编辑你的代码。

关于android - 使用线程显示进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10782344/

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