[英]ProgressDialog working in thread on android
我有一個小問題,希望您能幫助我;)
麻煩的是,ProgressDialog僅在加載run()之后才顯示,但是我需要在啟動時顯示它,並在加載一些數據時顯示它。 我把:“對話框= ProgressDialog.show(CategoriesListActivity.this,”正在工作...“,”正在加載數據“,true);” 在方法run()中,但相同。 我在Log.i()中打印一些信息(int i ++),然后輸入ProgressDialog的標題。 方法正常工作,但不顯示ProgressDialog。 我已經閱讀了一些信息,該信息表明某個線程阻塞了另一個線程(我創建的線程),這就是為什么不顯示progressDialog但卻無法執行任何操作的原因。 謝謝。
public void run() {
/** getting there long execution **/
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// stop and hide dialog
dialog.dismiss();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_
dialog = ProgressDialog.show(CategoriesListActivity.this, "Working...",
"Loading data", true);
// start new thread where get long time execution
Thread thread = new Thread(this);
thread.start();
//wait while data is loading, 'cause I need use variable from calculation
// in "EfficientAdapter" later
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ListView l1 = (ListView) findViewById(R.id.list);
l1.setAdapter(new EfficientAdapter(this));
}
這是借助AsyncTask (智能背景線程)和ProgressDialog的幫助完成的
當AsyncTask啟動時,我們將引發狀態不確定的進度對話框,一旦任務完成,我們將關閉該對話框。
范例程式碼
適配器在此示例中的作用並不重要,而更重要的是要了解您需要使用AsyncTask來顯示進度對話框。
private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
/* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected ContactsListCursorAdapter doInBackground(Void... params) {
cur1 = objItem.getContacts();
startManagingCursor(cur1);
adapter1 = new ContactsListCursorAdapter (viewContacts.this,
R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});
return adapter1;
}
protected void onPostExecute(ContactsListCursorAdapter result) {
list.setAdapter(result);
dialog.dismiss();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.