添加到相对布局动态时,ImageView没有边距

时间:2014-05-15 01:13:59

标签: android imageview relativelayout dynamic-programming margins

如果将layoutparams添加到视图中,我在relativelayout中添加Imageview时遇到问题,imageview将不会添加,但如果imageview没有layoutparams,它将显示但没有图像。 Imageview是通过代码创建的。

TableLayout imageCon = (TableLayout)root.findViewById(R.id.home_screen_table_imagecon);
TableRow imageTableRow = new TableRow(root.getContext());
    TableRow.LayoutParams rowSpanLayout = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

imageTableRow.addView(getLove());
imageTableRow.addView(getHappy());
imageCon.addView(imageTableRow,rowSpanLayout);
imageCon.setShrinkAllColumns(true);

private ImageView getLove(){
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(10, 10, 10,10);
    imgLove.setLayoutParams(lp);
    imgLove.setImageResource(R.drawable.img_emo_love);

    return imgLove;
}
private ImageView getHappy(){
    imgHappy.setImageResource(R.drawable.img_emo_happy);
    return imgHappy;
}

我期待着你的帮助。

由于 Chkm8

2 个答案:

答案 0 :(得分:1)

您需要使用TableRow.LayoutParams,因为您将ImageView添加到TableRow

LayoutParams更改为

TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,  TableRow.LayoutParams.MATCH_PARENT);
lp.setMargins(10, 10, 10,10);
imgLove.setLayoutParams(lp);

如果将ImageView添加到RelativeLayout,请使用RelativeLayout.LayoutParams

如果将ImageView添加到LinearLayout,请使用LinearLayout.LayoutParams

答案 1 :(得分:0)

将下面的行放在xml ImageView标记

android:adjustViewBounds="true"

...享受