0

我有一个异步任务。

protected class InitTask extends AsyncTask<Context, Integer, String> {

        View eachLayout;

        @Override
        protected String doInBackground(Context... params) {

            try {
                myfunction();
            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);


        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            linearLayout.invalidate();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            linearLayout.addView(eachLayout, params);
            linearLayout.invalidate();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onCancelled()
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        public void redrawLayout(View linearLayout) {
            try {

                eachLayout = linearLayout;
                publishProgress();

            } catch (Exception e) {

                e.printStackTrace();

            }
        }

    }


private void myFunction() {
        LayoutInflater layoutInflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        params = new LinearLayout.LayoutParams(
                newLinearLayout.getLayoutParams().width,
                newLinearLayout.getLayoutParams().height);

        for (int i = 0; i < list.size(); i++) {
            final View eachLayout = layoutInflater.inflate(R.layout.sample, null);
            //..........................
            eachLayout.invalidate();
            initTask.redrawLayout(eachLayout);
        }

    }


 params = new LinearLayout.LayoutParams(
                linearLayout.getLayoutParams().width,
                linearLayout.getLayoutParams().height);

它在这一行显示IllegalStateException linearLayout.addView(eachLayout, params); .(这个孩子已经有一个父母)。

我试过 linearLayout.removeAllViews() 等......但它不起作用。

如何解决这个问题?

提前致谢

4

2 回答 2

0

尝试以下操作:

@Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

       if( ((LinearLayout) eachLayout.getParent()) != null 
                &&  eachLayout != null) {
             ((LinearLayout) eachLayout.getParent()).removeView(eachLayout);
       }

        linearLayout.addView(eachLayout, params);
        linearLayout.invalidate();
    }
于 2012-09-04T10:22:36.757 回答
0

第一次将 eachLayout 添加到某个视图时,没关系。但是当你第二次做同样的事情时, eachLayout 已经有了父级。因此,尝试将其添加到任何视图都会失败。试试 Chintan Raghwani 的建议。

于 2012-09-04T10:28:41.923 回答