I want to add an unknown number of ImageView
views to my layout with margin. In XML, I can use layout_margin
like this:
<ImageView android:layout_margin="5dip" android:src="@drawable/image" />
There is ImageView.setPadding()
, but no ImageView.setMargin()
. I think it's along the lines of ImageView.setLayoutParams(LayoutParams)
, but not sure what to feed into that.
Does anyone know?
android.view.ViewGroup.MarginLayoutParams
has a method setMargins(left, top, right, bottom)
. Direct subclasses are: FrameLayout.LayoutParams
, LinearLayout.LayoutParams
and RelativeLayout.LayoutParams
.
Using e.g. LinearLayout
:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);
This sets the margins in pixels. To scale it use
context.getResources().getDisplayMetrics().density