【问题标题】:android background activities for laying out views用于布局视图的 android 后台活动
【发布时间】:2012-05-09 00:29:54
【问题描述】:

我需要将 30 多张图片加载到一个页面(带有预告文字)。我通过 AsyncTask 加载所有图像,但我无法修改当前布局,因为您只能对主线程上的视图执行修改。异步加载所有内容的最佳方式是什么,这样我的应用就不必在“页面加载”期间挂起?

【问题讨论】:

    标签: android android-layout android-asynctask


    【解决方案1】:

    我认为您不能在后台构建视图。最好的办法是显示一个进度对话框,以便用户了解应用为何忙碌。

    【讨论】:

    • 如果任务不在单独的线程上运行,进度对话框也会被阻止。
    【解决方案2】:

    如果你的类扩展了活动,你可以使用

    runOnUiThread(new Runnable() {
        public void run() {
            //Update UI elements in this block
        }  
    });
    

    【讨论】:

    • 它将在主线程上运行,因为它将被排队。至于你加载图片的线程,它仍然会继续运行。
    【解决方案3】:

    为什么不能修改布局?对于AsyncTask,你有onProgressUpdate 保证在UI 线程上运行。您只需要在您的doInBackground 代码中调用publishProgress

    ==更新==

    private class LoadImageTask<Url, String, String> extends AsynTask{
        doInBackground(Url... urls){
            for(int i=0; i<urls.length; i++){
                File img = DownloadImage(urls[i]); // Your download method.. 
                publishProgress(img.filename);     // Suppose it is saved in sd card
                // publish progress will call onProgressUpdate immediately, but on different thread
            }
        }
    
        onProgressUpdate(String filename){
            // Update the UI.. this method will run on UI thread
            displayImage(filename);
        }
    }
    

    【讨论】:

    • 这仍然会异步运行吗?还是它会“暂停”我的主线程?
    • onProgressUpdate 将暂停,因此仅使用它更新 UI。加载应该在 doInBackground 中完成。检查我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多