How to Set Margin of Imageview Using Code, Not Xml

How to set margin of ImageView using code, not xml

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);

MarginLayoutParams

This sets the margins in pixels. To scale it use

context.getResources().getDisplayMetrics().density

DisplayMetrics

Set Margin to Multiple ImageView Programmatically

first get Layout params like this

LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) imageView.getLayoutParams();

then set margins

Setting margins for an imageview dynamically

You're probably looking for something like this: http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)

Note this part of the method description though:

These supply parameters to the parent of this view specifying how it
should be arranged

Which means that if you have an ImageView inside of a LinearLayout, you need to supply the method with LinearLayout.LayoutParams, like this:

ImageView image = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
params.setMargins(1, 1, 1, 1);
image.setLayoutParams(params);

And then you just call setMargins or set the specific leftMargin, bottomMargin etc. properties of the LayoutParams.

how to set margin on imageview using code in android?

you are using LinearLayout.LayoutParams where the layout is RelativeLayout. change to RelativeLayout.LayoutParams, it should work.

how to set image's margin top using coding not xml in android

Use

public void setMargins (int left, int top, int right, int bottom) 

In Android, how do I set margins in dp programmatically?

You should use LayoutParams to set your button margins:

LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);

Depending on what layout you're using you should use RelativeLayout.LayoutParams or LinearLayout.LayoutParams.

And to convert your dp measure to pixel, try this:

Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);

android set margin programmatically

Try this code:

parameter =  (RelativeLayout.LayoutParams) txtField.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
txtField.setLayoutParams(parameter);


Related Topics



Leave a reply



Submit