ProgressBar in Android
How to implement a progress bar in this example?
package org.postandget;
import org.postandget.R;
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<1000;i++)
{
System.out.println(i);
开发者_StackOverflow }
}
}
While the loop executing i have to show a progressbar. I have worked on few examples, but nothing got right. Can any one help me?
here is simple example of Progresss Dialog
Example 1
Example 2
Code Snippet
package org.postandget;
import org.postandget.R;
public class main extends Activity {
ProgressDialog bar;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new BackgroundTask().execute("Main");
}
class BackgroundTask extends AsyncTask<String , Integer, Void>
{
@Override
protected void onPreExecute()
{
bar = new ProgressDialog(main.this);
bar.setMessage("Processing..");
bar.setIndeterminate(true);
bar.show();
}
@Override
protected Void doInBackground(String... params)
{
for(int i=0;i<10;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
bar.dismiss();
}
}
}
The proper way to deal with progress while performing a task is by implementing AsyncTask. It has the logic in place to perform a task in a background thread, while updating progress from the UI thread. Check the reference, and google for examples:
http://developer.android.com/reference/android/os/AsyncTask.html
The cleanest way to this this kind of operation is by using AsyncTask.Use onPreExecute() to show your ProgressDialog, doInBackground to do your stuff and onPostExecute to dismiss your ProgressDialog. ---
http://brighthub.com/mobile/google-android/articles/82805.aspx
精彩评论