简体   繁体   English

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

[英]ImageView no margin when added to Relative Layout Dynamic

I'm having problem when adding the Imageview in my relativelayout if a layoutparams is added to the view, the imageview will not add but if the imageview has no layoutparams, it will show but no image. 如果在我的相对布局中添加Imageview时遇到问题,如果将layoutparams添加到视图中,则不会添加imageview,但是如果imageview没有layoutparams,它将显示但没有图像。 Imageview is created through code. 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;
}

I'm looking forward for your help guys. 我期待着您的帮助。

Thanks Chkm8 谢谢Chkm8

You need to use the TableRow.LayoutParams , since your adding the ImageView into a TableRow 您需要使用TableRow.LayoutParams ,因为您将ImageView添加到TableRow

Change the LayoutParams as LayoutParams更改为

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

If ImageView is added to a RelativeLayout then use RelativeLayout.LayoutParams 如果将ImageView添加到RelativeLayout则使用RelativeLayout.LayoutParams

If ImageView is added to a LinearLayout then use LinearLayout.LayoutParams 如果将ImageView添加到LinearLayout则使用LinearLayout.LayoutParams

put below line in xml ImageView tag 放在xml ImageView标记的行下面

android:adjustViewBounds="true"

enjoy... 请享用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM