0

when declaring some element (let's say a Button) and giving it some width and height (let's say 200dp) from the XML file, I got certain result when running, although when make the same steps but Programmatically I got much smaller width and height, and this case happens only with me in Nexus tablets.

enter image description here

Manfred Moser
  • 29,539
  • 13
  • 92
  • 123
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
  • Keep in mind that some `setSize()` methods take pixels as an argument and not DPs. So you will need to convert your desired DPs to pixels first. See first answer here: http://stackoverflow.com/questions/4605527/converting-pixels-to-dp – Blacklight Oct 29 '14 at 10:06
  • @Blacklight great, that really answer my question, all the other devices in the world was working right with the same amount and that make me consider that the unit I'm using always is in dip and didn't know that some dip and some px, you are free to add an answer – Muhammed Refaat Oct 29 '14 at 10:18

1 Answers1

0

If you set the size of a View programmatically, many times pixels are taken as an argument. You will need to convert your desired size in DPs to pixels first, and use those to set the width or height of your element:

float dp = 200;
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

See the API-docs of the specific Views for infos about what kind of dimensions are taken as an argument.

Blacklight
  • 3,809
  • 2
  • 33
  • 39