0

我正在尝试添加一些对象,TableRow但出现以下错误:

05-11 13:43:34.494: E/AndroidRuntime(3258): FATAL EXCEPTION: main
05-11 13:43:34.494: E/AndroidRuntime(3258): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
05-11 13:43:34.494: E/AndroidRuntime(3258):     at android.view.ViewGroup.addViewInner(ViewGroup.java:3618)
05-11 13:43:34.494: E/AndroidRuntime(3258):     at android.view.ViewGroup.addView(ViewGroup.java:3489)
05-11 13:43:34.494: E/AndroidRuntime(3258):     at android.widget.TableLayout.addView(TableLayout.java:425)
05-11 13:43:34.494: E/AndroidRuntime(3258):     at android.view.ViewGroup.addView(ViewGroup.java:3434)

这是我的代码:

public class LruView extends TableLayout
{
    private Context c;

    public LruView(Context context, AttributeSet attrs) 
    {
        super(context, attrs);

        this.c = context;
    }

    public LruView(Context context) 
    {
        super(context);

        this.c = context;
    }

    public void setData(BaseAdapter mAdapter)
    {
        int columnCounter = 0;
        int totalColumns = getNumColumns();

        for (int i = 0; i < mAdapter.getCount(); i++)
        {
            if (i < totalColumns)
            {
                TableRow mTableRow = new TableRow(c);

                for (int j = 0; j < totalColumns; j++)
                {                   
                    View mView = mAdapter.getView(columnCounter, null, null);

                    mTableRow.addView(mView);

                    this.addView(mTableRow);

                    columnCounter++;                    
                }
            }
        }
    }

    public int getNumColumns()
    {
        float scalefactor = getResources().getDisplayMetrics().density * 100;

        int number = ((Activity) c).getWindowManager().getDefaultDisplay().getWidth();
        int columns = (int) ((float) number / (float) scalefactor);
        int deviceOrientation = getResources().getConfiguration().orientation;

        if (Configuration.ORIENTATION_LANDSCAPE == deviceOrientation)
            return ((columns - 3) <= 2) ? 3 : (columns - 3);
        else
            return ((columns - 1) <= 2) ? 2 : (columns - 1); 
    }
}

关于如何做到这一点的任何想法?

4

1 回答 1

0

问题是您正在尝试将视图添加到已经有父级的 TableRow 中,在这一行中:

View mView = mAdapter.getView(columnCounter, null, null);

因此,我将执行以下操作:我将创建一个布局,用于将其添加到表格行中。然后我以与您相同的方式获得我想要的数据,如下所示:

View mView = mAdapter.getView(columnCounter, null, null);

并使用 mView 的数据进行布局,当然是在膨胀之后。然后我将布局添加到 TableRow。基本上是这样的:

LayoutInflater inflater = LayoutInflater.from(context);
View layout = (View)inflater.inflate(R.layout.my_view_to_add);
View mView = mAdapter.getView(columnCounter, null, null);
//....get widgets from layout and set their data(i.e: text in a TextView)using what you fetch from mView.
....
mTableRow.addView(layout);
于 2013-05-11T13:05:56.950 回答