如何根据光标向表格布局添加额外的表格行?

时间:2011-02-22 08:27:20

标签: android cursor tablelayout

我的Android项目中的数据库中有一个包含不同结果的数据库。我想获取这些结果并在tablelayout中显示它们。在tablelayout中,我想为每个结果添加一行,并在一个textview上写“date”列,在第二个textview上写“result”。两个textview都在同一行。我获取数据并将其存储在游标中。

我的问题是:如何使用光标并根据数据库中的数据添加一行?

现在我尝试为游标中的每一行添加一行,如下所示:

TableLayout tl = (TableLayout)findViewById(R.id.table_layout2);
     TableRow tr = new TableRow(this);
     tr.setLayoutParams(new LayoutParams(
                             LayoutParams.FILL_PARENT,
                             LayoutParams.WRAP_CONTENT));
             TextView mTvDate = new TextView(this);
             TextView mTvResult = new TextView(this);
             int x=0;
             for(int i=0;i<c.getCount();i++){
             mTvDate.setText(date[x]);
             mTvResult.setText(""+nocorrect[x]+" av "+ noqs[x] +" ("+ proc[x]+ "%)");
             mTvDate.setLayoutParams(new LayoutParams(
                             LayoutParams.FILL_PARENT,
                             LayoutParams.WRAP_CONTENT));

             mTvResult.setLayoutParams(new LayoutParams(
                             LayoutParams.FILL_PARENT,
                             LayoutParams.WRAP_CONTENT));
             tr.addView(mTvDate);
             tr.addView(mTvResult);
     tl.addView(tr,new TableLayout.LayoutParams(
            LayoutParams.FILL_PARENT,
             LayoutParams.WRAP_CONTENT));
             }

但我认为我需要创建一个新的tablerow,因为我收到此错误消息:

02-22 09:22:17.543: ERROR/AndroidRuntime(333): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

但我不想删除它,我想添加更多。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

嗨试试这个 我想你每次都要添加相同的行。所以只需在每次循环迭代时声明它。

 TableLayout tl = (TableLayout)findViewById(R.id.table_layout2);

         int x=0;
         for(int i=0;i<c.getCount();i++){
 TableRow tr = new TableRow(this);
 tr.setLayoutParams(new LayoutParams(
                         LayoutParams.FILL_PARENT,
                         LayoutParams.WRAP_CONTENT));
         TextView mTvDate = new TextView(this);
         TextView mTvResult = new TextView(this);
         mTvDate.setText(date[x]);
         mTvResult.setText(""+nocorrect[x]+" av "+ noqs[x] +" ("+ proc[x]+ "%)");
         mTvDate.setLayoutParams(new LayoutParams(
                         LayoutParams.FILL_PARENT,
                         LayoutParams.WRAP_CONTENT));

         mTvResult.setLayoutParams(new LayoutParams(
                         LayoutParams.FILL_PARENT,
                         LayoutParams.WRAP_CONTENT));
         tr.addView(mTvDate);
         tr.addView(mTvResult);
 tl.addView(tr,new TableLayout.LayoutParams(
        LayoutParams.FILL_PARENT,
         LayoutParams.WRAP_CONTENT));
         }