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 widt开发者_开发百科h (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?
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);
}
float value = 12;
int unit = TypedValue.COMPLEX_UNIT_DIP;
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dipPixel = TypedValue.applyDimension(unit, value, metrics);
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());
精彩评论