I have an android application. There are a lot of buttons in it but these buttons are created during runtime. If i set the width button.setwidth(300)
it will set the width to 300px. I want the width to be set in dp. Is there any way around?
Asked
Active
Viewed 5,314 times
3

Mike T
- 4,747
- 4
- 32
- 52

user1438128
- 533
- 2
- 7
- 12
-
Use This http://stackoverflow.com/questions/5255184/android-and-setting-width-and-height-programmatically-in-dp-units – Anil Jadhav Jun 13 '12 at 07:38
-
Have a look at [this][1]. I think that's what you'll be wanting. [1]: http://stackoverflow.com/questions/5255184/android-and-setting-width-and-height-programmatically-in-dp-units – Mike T Jun 13 '12 at 07:39
3 Answers
12
You have to use TypedValue.applyDimension
to get the pixel count of dp's. Here's an example:
DisplayMetrics dm = getResources().getDisplayMetrics();
float dpInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DP, 300, dm);
That will give the the pixel value of 300dp programmatically.
Cheers

Zaid Daghestani
- 8,555
- 3
- 34
- 44
2
Android doen't have separate method for setting button's dimensions in dp. You have to:
//Find screen density scale factor
final float scale = getContext().getResources().getDisplayMetrics().density;
myButton.setWidth((int)(100 * scale));
myButton.setHeight((int)(50 * scale));

Ricardo Simmus
- 334
- 4
- 19
1
There's no setWidth(300dp). The workaround is to get the display size, and adjust the 300px variable accordingly.
I must say that there's probably a better way to create a nice layout. Have you tried using nested linearlayouts and layout_weights?

Christine
- 5,617
- 4
- 38
- 61