Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android and setting width and height programmatically in dp units

I'm doing:

button.setLayoutParams(new GridView.LayoutParams(65, 65));

According to the docs the units for the width and height (both 65 in the above) are "pixels". How do you force this to be device independent pixels, or "dp"?

like image 758
SK9 Avatar asked Mar 10 '11 03:03

SK9


People also ask

How to set height in dp programmatically android?

height = dpToPx(250);

How do I change the image size on Kotlin?

This example demonstrates how to resize Image in an Android App using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (dps * scale + 0.5f); 
like image 141
Robby Pond Avatar answered Oct 23 '22 23:10

Robby Pond