2012-02-20 132 views
0

我需要添加一些行到我的表格佈局和我需要添加兩個圖像按鈕的每一行。每次啓動活動時,行數都可能不同 - 我查看SQLite數據庫,並查看數據庫中的每一行,我需要添加一個圖像按鈕。在表格佈局的每一行中將會有兩個圖像按鈕。到目前爲止,我有這樣的代碼:ANdroid:動態添加圖像按鈕到表佈局中的行

db.open(); 
    int count = db.getCount(); 
    boolean newRow = true; 
    for (int i = 0; i < count; i++) { 
     if (newRow == true) { 
      newRow = false; 
      row = new TableRow(this); 
      row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,  LayoutParams.WRAP_CONTENT)); 
     } 
     ImageButton button = new ImageButton(this); 
     row.addView(button); 
     tableLayout.addView(row); 
    } 
    db.close(); 

的TableRow行的代碼簡單地作爲該活動變量這個塊定義如上。我的表佈局(tableLayout在代碼中)在活動佈局的XML代碼中定義:

<TableLayout 
    android:id="@+id/tableLayoutContacts" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 


</TableLayout> 

代碼崩潰在

tableLayout.addView(row);

我不是能夠解決這一行。有任何想法嗎?謝謝!!

+0

如何在Java代碼中指定您TableLayout? – 2012-02-20 08:03:17

+0

tableLayout =(TableLayout)findViewById(R.id.tableLayoutContacts); – 2012-02-20 08:26:51

+0

提供您的崩潰日誌。 – 2012-02-20 08:27:01

回答

0

我認爲這個問題是不同的

看來,你的代碼將只有一個行,你一次又一次地補充說行tableLayout,如下圖所示。

tableLayout.addView(row); 

這將導致IllegalStateException異常的ViewGroup處的

功能addViewInner

試試這個

db.open(); 
    int count = db.getCount(); 
    boolean newRow = false; 
    for (int i = 0; i < count; i++) { 
     if (i % 2 == 0) 
      newRow = true; 
     if (newRow == true) { 
      newRow = false; 
      row = new TableRow(this); 
      row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,  LayoutParams.WRAP_CONTENT)); 
      tableLayout.addView(row); 
     } 
     ImageButton button = new ImageButton(this); 
     row.addView(button); 

    } 
    db.close(); 
+0

哇,我總是沒有看到...但它現在有效,非常感謝! :)但似乎有另一個小問題...我認爲添加一個新的行會將它添加到前一個之下。但我現在只有一行(至少是光學)我的所有按鈕...任何提示?謝謝! :) – 2012-02-20 10:08:45

+0

嘗試編輯答案連續兩個按鈕 – 2012-02-20 11:35:44