2013-05-10 107 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