tags:

views:

106

answers:

2

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?

+2  A: 
float value = 12;
int unit = TypedValue.COMPLEX_UNIT_DIP;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dipPixel = TypedValue.applyDimension(unit, value, metrics);
JRL
+1  A: 

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);
}
Spike Williams
Now that your talking about your Utils class, that seems like a great place to put a lot of methods, and functions that are to be used by your main program or other classes, kind of like a global place to put things that are used many times by your program?
Allan
Thanks guys for the code. I'll add a conversion function to my application's Utils class. I'm new to Android. I can't help wondering why the setWidth method doesn't have the same built-in flexibility as setting the android:layout_width attribute in an XML layout.
JeffR