Runnable类内部的填充视图



我有一个实现可运行的类,它完成了一些任务,然后更新了一些视图:

public class DownloadPics implements Runnable {
    @Override
    public void run() {
        //retrieve data
        fillView(data);
    }
    public void refreshView(ArrayList<Object> new_pics) {
        LinearLayout linearLayout = (LinearLayout) ((Storico)context).findViewById(R.id.linearInsideScroll);
         View new_imageView = inflater.inflate(R.layout.history_element,
                null, false);
        //Build fill view

        linearLayout.addView(new_imageView);
    }
}

i在refreshView方法上调用addView时出错:

Only the original thread that created a view hierarchy can touch its views.

怎么了?

只有创建视图层次结构的原始线程才能接触其视图。

从后台线程更新ui。

您不能从后台线程更新ui。您可以从ui线程更新ui。

使用AsyncTask使其更容易。您可以在doInBackground中进行后台计算,并在onPostExecute 中更新ui

使用此方法runOnUiThread(Runnable action)

编辑

ASyncTaskrunOnUiThread 一起使用

class download extends AsyncTask<Void, Void, Void>
                    {
                        String message = "";
                        ProgressDialog dialog = new ProgressDialog(v.getContext());
                        @Override
                        protected void onPreExecute() 
                        {
                            // what to do before background task
                            dialog.setTitle("Downloading");
                            dialog.setIndeterminate(true);
                            dialog.setMessage(message);
                            dialog.setCancelable(false);
                            dialog.show();
                        }
                        void updateItem(int i) 
                        {
                            class UpdateItem implements Runnable 
                            {
                                int pos;
                                UpdateItem(int i) { pos = i; }
                                public void run() 
                                {
                                         dialog.setMessage(message);
                                }
                            }
                            runOnUiThread(new UpdateItem(i));
                        }
                        @Override
                        protected Void doInBackground(Void... params) {
                            downloadStuff();
                            i++
                            updateItem(i);
                        }
                        @Override
                        protected void onPostExecute(Boolean result) {
                            // what to do when background task is completed
                            dialog.dismiss();
                        };

                    };
                    new download().execute((Void[]) null);  

您需要一个来自在主线程上创建的处理程序的引用(请确保它是在主线程中创建的)。

Handler handler = new Handler();

在DownloadPics的run()方法中,您将使用:

handler.post(new Runnable(){
    public void run(){
        //update UI on main thread
    }
}

最新更新