2013-05-10 45 views
0

我試圖動態地將圖像添加到表中。爲此,我使用以下代碼:設置寬度和高度時,imageview消失

public void showLetter(String aLetter){ 
    TableLayout letterTable = (TableLayout) findViewById(R.id.letterArea); 
    TableRow letterRow = (TableRow) letterTable.getChildAt(0);  
    ImageView newLetter = new ImageView(this);  
    int imageResource = getResources().getIdentifier("a", "drawable", getPackageName()); 
    newLetter.setBackgroundResource(imageResource); 
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) new LinearLayout.LayoutParams(100, 50); 
    newLetter.setLayoutParams(params); 
    letterRow.addView(newLetter); 
} 

當我嘗試運行此代碼時,調用showLetter函數時不顯示圖像。當我沒有設置newLetter的佈局參數時,此功能起作用並顯示圖像。有沒有人知道爲什麼我不能設置這個圖像的佈局參數而不消失?

這是包含在其中的圖像應該添加表中的XML文件:

<TableLayout 
    android:id="@+id/letterArea" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/submitWord" 
    android:layout_marginLeft="@dimen/default_gap" 
    android:layout_marginRight="@dimen/default_gap" 
    android:layout_marginTop="@dimen/default_gap" > 

    <TableRow app:layout_gravity="fill_horizontal" > 

     <ImageView 
      android:layout_width="@dimen/blocksize" 
      android:layout_height="@dimen/blocksize" 
      android:background="@drawable/scrabble_a" /> 

     <ImageView 
      android:layout_width="@dimen/blocksize" 
      android:layout_height="@dimen/blocksize" 
      android:background="@drawable/scrabble_b" /> 

    </TableRow> 
</TableLayout> 

回答

1

刪除LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) new LinearLayout.LayoutParams(100, 50);(LinearLayout.LayoutParams)和檢查...

編輯

好吧我所看到的你的鱈魚是你的ImageView的父母是TableRow而不是LinearLayout

你可以檢查一次

TableRow.LayoutParams params = new TableRow.LayoutParams(100, 50); 

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) new LinearLayout.LayoutParams(100, 50); 
+0

這insetd並沒有對行爲產生任何影響。該圖像仍未顯示。 – Consec 2013-05-10 15:05:21

+0

你可以試試我在編輯中提出的建議。 – bakriOnFire 2013-05-10 15:10:42