指定的子项已具有父项.在表格布局中



我想每 1 列设置 1 张图像,但错误是指定的子级已经有父级。您必须先在孩子的父级上调用 removeView()。你能给我一个简单的解释吗.我该怎么办?

这是我的代码

 public class MybookActivity extends Activity{
private BooksDB db;
private Context context;
private HashMap< String, ArrayList<String>> hm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_mybook_sub2);
    ArrayList<String> list_bokID = new ArrayList<String>();
    ArrayList<String> list_title = new ArrayList<String>();
    ArrayList<String> list_theme = new ArrayList<String>();
    hm = new HashMap<String, ArrayList<String>>();

    context = this;
    db = new BooksDB(context);
    hm = db.getBookTheme();
    if(hm.isEmpty() == true){
        System.out.println("NO data");
    }else{
        System.out.println("have data");
        list_bokID = hm.get("bokID");
        for (String bokID : list_bokID){
            System.out.println(bokID);
        }
        list_title = hm.get("title");
        for (String title : list_title) {
            System.out.println(title);
        }
        list_theme = hm.get("theme");
        for (String themePath : list_theme) {
            System.out.println(themePath);
        }
    }
    int Theme_size = list_theme.size();
    //new
    int numRow = Theme_size / 2;
    int numCol = 5;
    TableLayout tblLayout = (TableLayout) findViewById(R.id.tblLayout);
    for(int i = 0; i < numRow; i++) {
        HorizontalScrollView HSV = new HorizontalScrollView(this);
        HSV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        TableRow tblRow = new TableRow(this);
        tblRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        tblRow.setBackgroundResource(R.drawable.newshell);
        for(int j = 0; j < numCol; j++) {
            ImageView imageView = new ImageView(this);
            for (String string : list_theme) {
                int res_id = getResources().getIdentifier(string, "drawable", getPackageName());
                imageView.setImageResource(res_id);
                tblRow.addView(imageView,j);
            }
        }
        HSV.addView(tblRow);
        tblLayout.addView(HSV, i);
    }
}


}

谢谢

您需要添加的每个图像视图(以及添加到 ViewGroup 的任何视图)的新实例。

在 for 内部循环中移动实例创建:

for (String string : list_theme) {
   ImageView imageView = new ImageView(this);
   int res_id = getResources().getIdentifier(string, "drawable", getPackageName());
   imageView.setImageResource(res_id);
   tblRow.addView(imageView,j);
}

最新更新