我試圖執行代碼showing dialog while loading layout by setContentView in background和http://developer.android.com/guide/appendix/faq/commontasks.html#threading以顯示加載對話框,同時我的活動正在加載,但有困難。Android:加載活動對話框
我有其上裝載另一個線程從數據庫中的數據在我的視圖中的UI元素定義的類的變量,並且還字符串:
private TextView mLblName, mLblDescription, etc...
private String mData_RecipeName, mData_Description...
我還處理程序定義:
private ProgressDialog dialog;
final Handler mHandler = new Handler();
final Runnable mShowRecipe = new Runnable() {
public void run() {
//setContentView(R.layout.recipe_view);
setTitle(mData_RecipeName);
mLblName.setText(mData_RecipeName);
mLblDescription.setText(mData_Description);
...
}
};
在的onCreate,我想也顯示對話框,然後產卵加載線程:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
setContentView(R.layout.recipe_view);
showData();
}
protected void showData() {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
mDatabaseAdapter = new ChickenPingDatabase(ShowRecipe.this);
mDatabaseAdapter.open();
mTabHost = getTabHost();
mLblName = (TextView)findViewById(R.id.lblName);
mLblDescription = (TextView)findViewById(R.id.lblDescription);
...
Cursor c = mDatabaseAdapter.getRecipeById(mRecipeId);
if(c != null){
mData_RecipeName= c.getString(c.getColumnIndex(Recipes.NAME));
mData_Description= c.getString(c.getColumnIndex(Recipes.DESCRIPTION));
...
c.close();
}
String[] categories = mDatabaseAdapter.getRecipeCategories(mRecipeId);
mData_CategoriesDesc = Utils.implode(categories, ",");
mHandler.post(mShowRecipe);
}
};
t.start();
}
這會加載數據,但不顯示進度對話框。我試着洗牌調用產生單獨的線程並顯示對話框,但無法顯示對話框。看起來這是一個相當普遍的要求,這篇文章似乎是它唯一回答的例子。
編輯:作爲參考,a blog post demonstrating the way I eventually got this working。
沒問題!您提供自己的博客文章的鏈接?您可以通過重寫onPreExecute()並在其中顯示對話框而不是onCreate來進一步使用AsyncTask的方法。確保你也測試了你的應用程序如何改變方向時的反應。確保正確處理AsyncTask,以便它不會丟失它的上下文。 @Commonsware在這裏做了一個很好的演示:http://bit.ly/gFYzsP – Zarah 2011-02-27 15:31:38