嘗試下面的代碼
public class YourActivity extends ListActivity{
private ProgressDialog progressBar;
private Animation rotation;
private DownloadXmlTask downloadXmlTask;
private Boolean Loading=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_main);
doDownload();
}
private void doDownload()
{
if (isConnectedToInternet()){
downloadXmlTask=new DownloadXmlTask();
downloadXmlTask.execute();
}
else
Toast.makeText(YourActivity.this,"faild connection", 1).show();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Loading==true)
stopLoadingAndDownloading();
}
//=====================
//New Class Starts Here
//=====================
class IconicAdapter extends ArrayAdapter<String> {
//your class
}
public void onListItemClick(ListView parent, View v, int position,
long id){
//do something
}
/*-----------------------------------------------------------------------------------
* Showing/Stopping progress dialog which is showing loading animation
* ---------------------------------------------------------------------------------*/
private void showLoading(){
progressBar = ProgressDialog.show(YourActivity.this, "", "");
progressBar.setContentView(R.layout.YourLayout);
progressBar.setCancelable(false);
//and another thing that need for progressBar
Loading=true;
}
private void stopLoadingAndDownloading() {
Loading=false;
if(progressBar.isShowing())
progressBar.dismiss();
if (downloadXmlTask != null && downloadXmlTask.getStatus() != AsyncTask.Status.FINISHED)
downloadXmlTask.cancel(true);
}
public boolean isConnectedToInternet(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
/*********************************************************
* this class is a useful class that prevent from crashing
* when download of data take very long time
*********************************************************/
private class DownloadXmlTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
showLoading();
}
@Override
protected String doInBackground(Void... esult) {
//doing your download from internet
return msg;
}
@Override
protected void onPostExecute(String result) {
//do something
setListAdapter(new IconicAdapter());
stopLoadingAndDownloading();
}
}
}
兩個詞:['AsyncTask'](http://developer.android.com/reference/android/os/AsyncTask.html)和['ProgressDialog'](http://developer.android.com/reference/android/app/ProgressDialog.html)。 – m0skit0
但是,如何通知適配器,有任何數據要使用? – Mariusz
直到有數據時才需要創建適配器。獲得數據後,填充適配器並關閉進度對話框。 – m0skit0