-5

I have a set of ImageViews whose BackgroundResource and LayoutParams will be defined in a separate xml file. The height, width, marginleft and margintop are given in pixels. The values are in respect to a 1024x600 pixel resolution screen. The code i'm using

    ImageView ImgV= (ImageView)findViewById(R.id.ImgV_1);
    RelativeLayout.LayoutParams the_dimens = new RelativeLayout.LayoutParams(50,50);
    the_dimens.setMargins(800,50,0,0);

    ImgV.setBackgroundResource(R.drawable.bulbon);
    ImgV.setLayoutParams(the_dimens);

While the height and width seem to be rightly displayed in pixels, the margins are not. So how can I set the margin values to apply in pixels rather than whatever default units the below code takes. the_dimens.setMargins(800,50,0,0);

The app is only for a 1024x600 device, so i'm not worried about resolution independent design. Thanks.

Sri
  • 23
  • 7
  • 2
    the official docs for `ViewGroup.MarginLayoutParams` say: `setMargins(int left, int top, int right, int bottom) Sets the margins, in pixels. [...]` – pskink Aug 31 '16 at 11:21
  • @pskink i've checked and measured the values in photoshop. they don't add up – Sri Aug 31 '16 at 11:23
  • @pskink if it isn't showing right in the emulator (which is 1024x600 res) i doubt it will be the case in the actual device. I think im missing something here.. – Sri Aug 31 '16 at 11:26
  • @pskink you are right. it is my mistake. the root relative layout had padding. i think i should be more careful before posting here. thank you for your time :) – Sri Aug 31 '16 at 12:22
  • no problem really – pskink Aug 31 '16 at 13:04

2 Answers2

0

check this

int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels
Community
  • 1
  • 1
huk
  • 220
  • 3
  • 11
0

You can do in this way:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);
Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80