Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 357
JeffR Avatar asked Jul 31 '10 22:07

JeffR


2 Answers

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);
}
like image 109
Spike Williams Avatar answered Sep 20 '22 22:09

Spike Williams


float value = 12;
int unit = TypedValue.COMPLEX_UNIT_DIP;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dipPixel = TypedValue.applyDimension(unit, value, metrics);
like image 44
JRL Avatar answered Sep 19 '22 22:09

JRL