创建多个(数百个)视图时活动冻结

时间:2013-11-12 23:58:58

标签: android android-activity dialog android-asynctask freeze

我需要创建一个表,每个单元格的列宽不同。我有~20行和60-80列。这是我的代码:

private void generatingRows() {

    new AsyncTask<Void,View,Void>() {

        private ProgressDialog dialog;
        private int progress = 0;

        @Override
        protected void onPreExecute() {

            // Clear table
            table.removeAllViews();

            // Show peogress dialog
            dialog = new ProgressDialog(MyActivity.this);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage("Loading");
            dialog.setCancelable(false);
            dialog.setMax(data.size);
            dialog.setProgress(0);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {


            for (final RowData rowData : data) {

                // Create row
                LinearLayout row = new LinearLayout(MyActivity.this);
                row.setOrientation(LinearLayout.HORIZONTAL);

                // Add columns
                for (int i = 0; i < rowData.columns.size(); i++) {

                    // Get column values
                    final ColumnData columnData = rowData.columns.get(i);

                    // Get view
                    final View column = layoutInflater.inflate(R.layout.column, null);

                    // Set values
                    MyActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView.class.cast(column.findViewById(R.id.title)).setText(columnData.title);
                        }
                    });

                    // Add into row
                    row.addView(column);
                }

                // Update
                progress++;
                publishProgress(new View[] {channelItem, showRow });

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(View... resultViews){
            dialog.setProgress(progress);
            table.addView(resultViews[0]);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
        }

    }.execute();

}

“table”视图是一个垂直方向的LinearLayout。问题是对话框出现了,但冻结,只更新一次,两次,而不是每一行。当然,如果我在onProgressUpdate方法中跳过addView而不是完美地工作,那么进展是连续的。我不能在后台添加行,那么解决方案是什么?

0 个答案:

没有答案