Java 关于Android进度条工作
我对android中的进度条有疑问。我还没有实施它,但由于时间不够,我想确保在实施时,我最好清楚将要发生什么以及为什么Java 关于Android进度条工作,java,android,android-layout,Java,Android,Android Layout,我对android中的进度条有疑问。我还没有实施它,但由于时间不够,我想确保在实施时,我最好清楚将要发生什么以及为什么 dialog = new ProgressDialog(this); dialog.setCancelable(true); dialog.setMessage("Loading..."); // set the progress to be horizontal dialog.setProgressStyle(P
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// get the maximum value
EditText max = (EditText) findViewById(R.id.maximum);
// convert the text value to a integer
int maximum = Integer.parseInt(max.getText().toString());
// set the maximum value
dialog.setMax(maximum);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread (new Runnable() {
public void run() {
try {
// enter the code to be run while displaying the progressbar.
//
// This example is just going to increment the progress bar:
// So keep running until the progress value reaches maximum value
while (dialog.getProgress()<= dialog.getMax()) {
// wait 500ms between each update
Thread.sleep(500);
// active the update handler
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
}
};
dialog=newprogressdialog(此);
对话框。可设置可取消(true);
setMessage(“加载…”);
//将进度设置为水平
设置ProgressStyle(ProgressDialog.STYLE_水平);
//将条形图重置为默认值0
对话框。设置进度(0);
//获取最大值
EditText max=(EditText)findViewById(R.id.max);
//将文本值转换为整数
int max=Integer.parseInt(max.getText().toString());
//设置最大值
dialog.setMax(最大值);
//显示进度条
dialog.show();
//创建用于更新进度条的线程
线程背景=新线程(newrunnable(){
公开募捐{
试一试{
//输入显示进度条时要运行的代码。
//
//本例只是增加进度条:
//因此,继续运行,直到进度值达到最大值
而(dialog.getProgress()您应该使用AsynTask并在其onPreExecute()
方法中显示ProgreesBar,并在其onPostExecute()方法中关闭ProgressBar。在doInBackground()
方法中执行所有加载操作。此外,要更新ProgressBar,请使用onProgressUpdate()
这将有所帮助:我认为您缺少的概念是,如果您想要完成多个任务(在进度条中显示进度并执行一些实际工作),您需要使用多个线程。这就是为什么您需要创建一个单独的线程来执行实际工作的原因
即使您的代码确实很长,也可以尝试重新分解它,将其拆分为新的类和方法。那么您的意思是说,如果在该部分中保留嵌套for循环,则进度条将不断更新多个线程的原因?它仍然应该是动画的,因为您是在单独的线程中进行工作的。但是,您仍然需要告诉主线程通过嵌套循环中的某个进度处理程序执行进度。