设置宽度和高度时,imageview消失

时间:2013-05-10 14:46:45

标签: android android-layout 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 个答案:

答案 0 :(得分:1)

(LinearLayout.LayoutParams)删除LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) new LinearLayout.LayoutParams(100, 50);并检查...

修改

好的,我在你的鳕鱼中看到你的ImageView的父亲是TableRow而不是LinearLayout

您可以查看一次

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

插入

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