2

in my application , i use the method setMargins(....) for some views .

in my layout , i fixed the width , heigth and size of my views with 'dp' , not pixels ,

and in my code , when i set Margins , it gives a bad result , but when i change dp with px in my layout , that's work fine .

so my question is : can i set Margins with dp values , ?? example :

myView.setMargins(left in dp , top in dp , right in dp , bottom in dp ) ; 

thanks in advance

Houcine
  • 24,001
  • 13
  • 56
  • 83

1 Answers1

7

You can do that easily, just need to define Dimension elements (values strings.xml ) and reference them in your code.

This is line from strings.xml

<dimen name="left_border_distance">32dip</dimen>

but you do not need to put that directly, rather via IDE.

Then in your code

int marginLeft = (int) getResources().getDimensionPixelSize(R.dimen.left_border_distance);
myView.setMargins(marginLeft  , top in dp , right in dp , bottom in dp ) ;  
Halls
  • 63
  • 1
  • 5
Zelimir
  • 11,008
  • 6
  • 50
  • 45
  • hi , thanks for your quick answer :p , can you give me an example of that plz , Second : is there another way to do this without passing with res/values/strings.xml ?? Thanks Zelimir – Houcine May 18 '11 at 09:00
  • Another approach is described in the answer below. I prefer to put GUI design values to resources, and not to work with hardcoded values in the code. They are easy changeable from one place. – Zelimir May 18 '11 at 09:07
  • ur approach is good ,but i'm developping a sdk for ads, so i need to define that in Code , not in strings.xml :) – Houcine May 18 '11 at 09:13