Reputation: 533
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?
Upvotes: 3
Views: 5486
Reputation: 334
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));
Upvotes: 2
Reputation: 5575
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?
Upvotes: 1
Reputation: 8615
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
Upvotes: 12