如何在android中使用后台线程更新进度条?它还会改变进度条的进度。请帮忙。
AndroidVogue
答案 0 :(得分:3)
我使用AsyncTask
完成了类似的任务。 AsyncTask
有方法onProgressUpdate(Integer)
,您可以通过调用doInBackground()
来调用每次迭代,例如每次在publishProgress()
期间完成进度。
有关详细信息,请参阅docs。
答案 1 :(得分:2)
Thread t=new Thread()
{
public void run()
{
while(some condition)
{
sleep(1000);
Message myMessage = new Message();
myMessage.obj = "success";
handler.sendMessage(myMessage);
}
}
};
private Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg)
{
String result=(String)msg.obj;
if(result.equals("success")
{
//update progress bar here
}
}
};
答案 2 :(得分:1)
private ProgressBar pgb;
private TextView textview;
private int progressBarStatus = 0;
private Handler progressBarbHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
pgb = (ProgressBar) findViewById(R.id.progressBar2) ;
}
public void load_bar(View view)
{
pgb.setMax(100);
pgb.setProgress(0);
new Thread(new Runnable() {
@Override
public void run() {
for (progressBarStatus = 0; progressBarStatus <= 100; progressBarStatus++) {
progressBarbHandler.post(new Runnable() {
public void run() {
pgb.setProgress(progressBarStatus);
}
});
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}).start();
}
答案 3 :(得分:1)
// this is demonstrate how to update progress bar from a thread
private ProgressBar pgb; // is a progressBar named with pgb
private int progressBarStatus = 0;// is a variable named progressBarStatus and initialize by 0
// in onCreate method find the ui component view horizontal prograssbar named progressBar2
public void load_bar(View view) // is a button OnClick
// and i am using a thread with for loop to demonstrate a task and variable progressBarStatus as status
pgb = (ProgressBar) findViewById(R.id.progressBar2) ;// find view by id
pgb.setMax(100); // at this point we the maximum value of a progress bar to make it full like we make 100 pices of it
pgb.setProgress(0); // initialize the progress bar with 0 % progress
// progress bar handler that update the status of progress bar . without handler we cant update progress bar from thread
progressBarbHandler.post(new Runnable() {
public void run() {
pgb.setProgress(progressBarStatus);
}
答案 4 :(得分:0)
使用handler,此处理程序将更新进度条 你要做的是: 1)从你的线程向处理程序发送消息 2)更新处理程序中的进度条
答案 5 :(得分:0)
使用Thread可以做到这一点,只需在oncreate方法中调用函数
public void loadProgressbar()
{
progressBar.setMax(100);
progressBar.setProgress(0);
new Thread(new Runnable() {
@Override
public void run() {
for (progress = 0; progress <= 100; progress++) {
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progress);
}
});
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
}
}).start();
}