我已经编写了此代码,它试图在表格布局内添加表格行(其中包含文本视图)。这是在一个循环中完成的。我得到这个错误:将表格行添加到循环中的表格布局
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.testant/com.test.testant.products}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
我可以以某种方式覆盖父视图上的removeView()吗?如果我不能如何将removeView()集成到我的代码中?
products.java
public class products extends Activity{
private DataBaseManager dataBase;
//put the table name and column in constants
public static final String TABLE_NAME_PRODUCTS = "products";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.products);
TableLayout tl = (TableLayout) findViewById(R.id.prodTable);
TableRow tr = (TableRow) findViewById(R.id.prodRow);
//creates and open the database so we can use it
dataBase = DataBaseManager.instance();
Cursor cursor = dataBase.select("SELECT * FROM " + TABLE_NAME_PRODUCTS);
while (cursor.moveToNext()){
tl.addView(tr);
}
}
products.xml
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/prodTable">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="false"
android:id="@+id/prodRow">
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".08"
android:textColor="#fff"
android:id="@+id/prodCodeView"
android:clickable="true" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".30"
android:textColor="#fff"
android:id="@+id/prodNameView"
android:clickable="true" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".05"
android:textColor="#fff"
android:id="@+id/prodMUView" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".10"
android:textColor="#fff"
android:id="@+id/prodPriceView" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".05"
android:textColor="#fff"
android:id="@+id/prodVATView" />
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".05"
android:textColor="#fff"
android:id="@+id/prodIDView" />
</TableRow>
</TableLayout>
findViewByID()不会创建一个新的对象,它只返回已经存在的对象 - 对同一个实例的另一个引用,在这里不会改善情况。 – Mjoellnir 2014-09-29 08:11:00
没错。错过了他在复制时使用了findViewById。谢谢:) – 2014-09-29 08:12:16
不客气:) – Mjoellnir 2014-09-29 08:13:06