0

我正在尝试通过在后台通过 setContentView 加载布局时显示对话框http://developer.android.com/guide/appendix/faq/commontasks.html#threading在我的活动加载时显示加载对话框来实现代码,但有困难。

我为视图中的 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();
}

这会加载数据,但不会显示进度对话框。我尝试改组调用以生成单独的线程并显示对话框,但无法显示对话框。这似乎是一个相当普遍的请求,而这篇文章似乎是唯一得到回答的例子。

编辑:作为参考,一篇博客文章展示了我最终得到这个工作的方式

4

1 回答 1

1

由于您想要的非常简单,因此我建议您使用AsyncTask。您可以在 onPreExecute() 和 onPostExecute() 中控制对话框的显示/隐藏。查看链接,那里有一个很好的例子。

于 2011-02-27T14:21:57.587 回答