MarginLayoutParams.setMargins() is not working?

橙三吉。 提交于 2019-12-14 01:27:53

问题


Here's the thing: I want to add some images programmatically. The images should have to have a topMargin of 5dip except for the first image, in a LinearLayout with a vertical orientation manner. below the code segment:

LinearLayout body = (LinearLayout) findViewById(R.id.body);

    for (int i = 1; i <= 4; i++) {

        ImageView img = new ImageView(this);
        MarginLayoutParams lp = new MarginLayoutParams(-2, -2);

        img.setImageResource(R.drawable.image);
        if (i != 1) {

            lp.setMargins(0, 5, 0, 0);

        }
        img.setLayoutParams(lp);

        body.addView(img);
        body.requestLayout();
    }

By running the program I can see the the 4 images(here) vertically aligned one by one but there is no topMargin(as in the code,5dip). body is the id of the LinearLayout. here's the XML segment to:

<LinearLayout
            android:id="@+id/body"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#901b0e08"
            android:orientation="vertical"
            android:paddingLeft="6dp"
            android:paddingRight="8dp" >
 </LinearLayout>

I cant get what went wrong here.

Thanks.


回答1:


Try changing your MarginLayoutParams to this:

LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );

The reason for doing this, is that body is a LinearLayout and thus you would want to use the LinearLayout-specific LayoutParams.




回答2:


Try to set padding but margin for ImageView. Sometimes it works fine. Your can directly set padding size to ImageView w/o declare LayoutParams.




回答3:


You probably need to set LayoutParams' gravity property, for example:

    lp.gravity = 0; //AXIS_X_SHIFT 

That's what works fine for me.



来源:https://stackoverflow.com/questions/8209091/marginlayoutparams-setmargins-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!