我在android中遇到了不确定的进展问题。我有一个按钮,单击按钮时会出现不确定的进度条,在任务结束时,进度条应该消失。
但我无法做到这一点。
package com.indeterminate;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.*;
public class IndeterminateProgressBarActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final ProgressBar pb=new ProgressBar(this);
pb.setVisibility(View.GONE);
Button b =new Button(this);
b.setText("Click to start spinning");
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
pb.setVisibility(View.VISIBLE);
// Want to write some code
pb.setVisibility(View.GONE);
// But the progress bar is not shown on the screen
LinearLayout l=new LinearLayout(this);
l.addView(pb);
l.addView(b);
this.setContentView(l);
}
}
答案 0 :(得分:1)
使用异步任务。在onClick电话
new SomeTask(0).execute();
/** Inner class for implementing progress bar before fetching data **/
private class SomeTask extends AsyncTask<Void, Void, Integer>
{
private ProgressDialog Dialog = new ProgressDialog(yourActivityClass.this);
@Override
protected void onPreExecute()
{
Dialog.setMessage("Doing something...");
Dialog.show();
}
@Override
protected Integer doInBackground(Void... params)
{
//Task for doing something
return 0;
}
@Override
protected void onPostExecute(Integer result)
{
if(result==0)
{
//do some thing
}
// after completed finished the progressbar
Dialog.dismiss();
}
}
答案 1 :(得分:1)
对于这个概念,你应该asynctask类
on preExecute你可以设置progressBar可见,在DoInBackGround你可以写你的代码,在PostExecute你可以设置progressBar Gone的可见性。
static class PleaseWait extends AsyncTask<void, void, Void> {
final ProgressBar pb = new ProgressBar(this); pb.setVisibility(View.GONE);
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
protected Void doInBackground(Object... args) {
//Write some code here
}
protected void onPostExecute(Void result) {
pb.setVisibility(View.GONE);
}
}
你可以调用新的PleaseWait()。执行;