JeffR
JeffR

Reputation: 313

How to programatically set the width of an Android EditText view in DPs (not pixels)

I'm dynamically generating a grid of EditText views in code based on a specified number of rows and columns. I want each of the EditText views to be the same width (e.g., 100dp).

Although I can set the size of the views with either setWidth or by creating a LayoutParam object, I only seem able to specify the value in pixels. I instead want to use the DP (density independent) units, similar to what I've done using an XML layout.

How can this be done in code?

Upvotes: 6

Views: 3573

Answers (3)

Aniruddha K.M
Aniruddha K.M

Reputation: 7521

Using the below code i was able to do it.

int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (100)your Size in int, getResources().getDisplayMetrics());

Upvotes: 0

Spike Williams
Spike Williams

Reputation: 37385

I have a method in a Utils class that does this conversion:

public static int dip(Context context, int pixels) {
   float scale = context.getResources().getDisplayMetrics().density;
   return (int) (pixels * scale + 0.5f);
}

Upvotes: 11

JRL
JRL

Reputation: 78033

float value = 12;
int unit = TypedValue.COMPLEX_UNIT_DIP;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dipPixel = TypedValue.applyDimension(unit, value, metrics);

Upvotes: 5

Related Questions