【问题标题】:You must call removeView () with the AddView in AsyncTask您必须在 AsyncTask 中使用 AddView 调用 removeView()
【发布时间】:2015-02-25 19:35:15
【问题描述】:

我动态创建一个表,如下所述 并且效果很好....

http://s24.postimg.org/wgofs717p/ex_Tables.png

mLinearLayout.removeAllViews()
MyTableLayout mTableLayout = new MyTableLayout(...);
for (int j = 0; j < numberOfTables; j++) {
    for i =0; i<numberOfLines; i++{
        View v = LayoutInflater.from(context).inflate(
        R.layout.line_layout,((ViewGroup) MyTableLayout.getChildAt(i)), false);
        ((TextView) v.findViewById(R.id.numeroRespostaDialogId)).setText("text");
        (ViewGroup) tableLayout.getChildAt(i)).addView(v);
        }
    mLinearLayout.addView(mTableLayout);
}

现在我需要把它放在 AsyncTask 中创建 而且我基本上做了同样的方法,没有 AsyncTask

protected ArrayList<MyTableLayout> doInBackground(Void... params) {
        mArray<MyTableLayout>
        MyTableLayout mTableLayout = new MyTableLayout(...);
        for (int j = 0; j < numberOfTables; j++) {
            for i =0; i<numberOfLines; i++{
                View v = LayoutInflater.from(context).inflate(
                R.layout.line_layout,((ViewGroup) MyTableLayout.getChildAt(i)), false);
                ((TextView) v.findViewById(R.id.numeroRespostaDialogId)).setText("text");
                (ViewGroup) tableLayout.getChildAt(i)).addView(v);
        }
        mArray.addView(mTableLayout);
    }
    return mArray;  
    }

    onPostExecute(){
        mLinearLayout.removeAllViews()
        for i=0  to mArray.size ++{
            mLinearLayout.addView(mArray[i]);
            }
        }

使用这个 AsyncTask 我得到了错误

  java.lang.IllegalStateException:指定的孩子已经有一个父母。您必须先在孩子的父母上调用 removeView()。

并将 removeAllViews () 放入 OnPostExecute 的“For” ... 工作但只显示最后一列; 如何使用 AsyncTask 迭代视图数组在 LinearLayout 中添加视图...

我不明白为什么 out of AsyncTask 工作,当我放入 AsyncTask 时得到错误

感谢您的帮助...

------编辑------ 这项工作... =/ 但是为什么不使用“For”

onPostExecute(){
  //for (int i = 0; i < myArray.size(); i++) {
    mLinearLayout.addView(myArray.get(0));
    mLinearLayout.addView(myArray.get(1));
    mLinearLayout.addView(myArray.get(3));
  //}
 }

// ----------EDIT2 --------

我不知道为什么..但是没有任何改变就可以工作=D

【问题讨论】:

  • IMO 您不应根据数据更改视图结构(添加/删除视图)。它速度慢、效率低、不优雅且容易出错。考虑使用适配器。您可以使用现有的适配器或创建自己的适配器并使用 ListViewAdapter 或类似中的模式。

标签: android android-asynctask android-linearlayout


【解决方案1】:

我通常会做这样的事情......

if(itemView.getParent() != null){
   ((ViewGroup)itemView.getParent()).removeView(itemView);
}

【讨论】:

  • 感谢您的回复,但现在它可以工作了,我使用的是相同的来源。我不知道之前出了什么问题
猜你喜欢
  • 2014-06-17
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多