我已經編寫了此代碼,它試圖在表格佈局內添加表格行(其中包含文本視圖)。這是在一個循環中完成的。我得到這個錯誤:將表格行添加到循環中的表格佈局
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