public class MyActivity extends Activity
{
/**
* Called when the activity is first created.
*/
ProgressBar progressBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.pb);
TextView view=(TextView) findViewById(R.id.myt);
new Task(view).execute();
}
通过在构造函数中传递 TextView 实例,我们可以在进度条中使用
private class Task extends AsyncTask<Void, Integer, Void> {
TextView view;
private Task(TextView textView) {
this.view= textView;
}
int myProgress;
@Override
protected void onPreExecute() {
myProgress = 0;
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MyActivity.this,
"onPostExecute", Toast.LENGTH_LONG).show();
super.onPostExecute(aVoid);
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
view.setText("Value"+myProgress);
super.onProgressUpdate(values);
}
@Override
protected void onCancelled() {
super.onCancelled(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected Void doInBackground(Void... voids) {
while (myProgress < 100) {
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}
}
}