Android specifying pixel units (like sp, px, dp) without using XML - android

Is it possible to specify the pixel unit in code.
What I mean is, say I have a layout and I want the size to be 20dp, then is there any way to do so without writing in a layout xml

In a view:
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
In an Activity, of course, you leave off the getContext().
To convert from scaled pixels (sp) to pixels, just use metrics.scaledDensity instead of metrics.density.
EDIT: As #Santosh's answer points out, you can do the same thing using the utility class TypedValue:
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
int pixels = Math.round(fpixels);
For sp, substitute TypedValue.COMPLEX_UNIT_SP for TypedValue.COMPLEX_UNIT_DIP.
Internally, applyDimension() does exactly the same calculation as my code above. Which version to use is a matter of your coding style.

You can use
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
now, the value of pixels is equivalent to 20dp
The TypedValue contains other similar methods that help in conversion

Related

Converting dp into pixels for multiple screen support

I am having a hard time to make this right.
Basically I am creating an ImageView and applying a LayoutParameter to it.
LayoutParams lp = new LayoutParams(width, height);
lp.gravity = Gravity.CENTER;
I know that width and height parameters receive pixel numbers, so I am passing them in DP and converting it to absolute pixels using:
public int convertToPixels(float dpSize){
final float density = getResources().getDisplayMetrics().density;
return ((int) (dpSize * density + 0.5f));
}
As far I know, this should make a drawable fill exactly the same area in different screens, right? Unfortunately, that is not happening at all.
Is there something wrong with these methods I am using?
These two emulators below have the same image and the same amount of DP.
Left emulator is 1.0 density and right one is 2.0. Why still does it look
so different ? Don't undertand..
Use :
public class Convert{
public static float convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
}
}
Just use it in a static way:
float requiredPixel = Convert.convertDpToPixel(16.0);
For more info: https://developer.android.com/guide/practices/screens_support.html

RectF use dp or px?

In Canvas, drawing an rectangle with RectF, need set top and left in dp or px?
Integer padding = 10;
Integer width = 100; // It is dp or px?
Integer height = 50;
RectF position = new RectF();
position.top = 0 + padding;
position.bottom = position.top + height;
position.left = 0 + padding;
position.right = position.left + width;
http://developer.android.com/intl/es/reference/android/graphics/RectF.html
It does not indicate if the values are represented in px or dp.
As has already been pointed out, Canvas and RectF use px and not dp.
As for the documentation, the documentation for Canvas
(http://developer.android.com/intl/es/reference/android/graphics/Canvas.html)
and RectF only mention pixels.
Since it is not explicitly pointed out that they are dp and both classes are directly derived from java.lang.Object, one can only conclude that it must be "normal" pixels.
If, for some reason, you need to convert from dp to px and vice versa, have a look at this document:
http://developer.android.com/intl/es/guide/practices/screens_support.html
It uses pixels, not density independent pixels.
It using pixel but if you want must convert it.
private int convertDpToPx(int dp){
return Math.round(dp * (getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
I hope it helps.

View.setPadding accepts only in px, is there anyway to setPadding in dp?

Android function View.setPadding(int left, int top, int right, int bottom) only accepts values in px but I want to set padding in dp. Is there any way around it?
Straight to code
int padding_in_dp = 6; // 6 dps
final float scale = getResources().getDisplayMetrics().density;
int padding_in_px = (int) (padding_in_dp * scale + 0.5f);
If you define the dimension (in dp or whatever) in an XML file (which is better anyway, at least in most cases), you can get the pixel value of it using this code:
context.getResources().getDimensionPixelSize(R.dimen.your_dimension_name)
There is a better way to convert value to dp programmatically:
int value = 200;
int dpValue = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
context.getResources().getDisplayMetrics());
Then apply dpValue to your method, for example: setPadding(dpValue,dpValue,dpValue,dpValue);
Here's Kotlin version based on accepted answer:
fun dpToPx(dp: Int): Int {
val scale = resources.displayMetrics.density
return (dp * scale + 0.5f).toInt()
}
You can calculate the pixels for a specific DPI value: http://forum.xda-developers.com/showpost.php?p=6284958&postcount=31
I've the same problem. The only solution i've found (it will not really help you :) ) is to set it in the Xml file.
If you can get the density from the code, you can use the convertion: "The conversion of dip units to screen pixels is simple: pixels = dips * (density / 160)." (from http://developer.android.com/guide/practices/screens_support.html )
Edit: you can get the screen density: http://developer.android.com/reference/android/util/DisplayMetrics.html#densityDpi

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?
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());

Does setWidth(int pixels) use dip or px?

Does setWidth(int pixels) use device independent pixel or physical pixel as unit?
For example, does setWidth(100) set the a view's width to 100 dips or 100 pxs?
Thanks.
It uses pixels, but I'm sure you're wondering how to use dips instead. The answer is in TypedValue.applyDimension(). Here's an example of how to convert dips to px in code:
// Converts 14 dip into its equivalent px
Resources r = getResources();
int px = Math.round(TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 14,r.getDisplayMetrics()));
The correct way to obtain a constant number of DIPs in code is to create a resources XML file containing dp values a bit like:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="image_width">100dp</dimen>
<dimen name="image_height">75dp</dimen>
</resources>
Then refer to the resource in your code like so:
float width = getResources().getDimension(R.dimen.image_width));
float height = getResources().getDimension(R.dimen.image_height));
The float you have returned will be scaled accordingly for the pixel density of the device and so you don't need to keep replicating a conversion method throughout your application.
Method setWidth(100), set 100 px as width(not in dp).So you may face width varying problems on different android phones.So use measurement in dp instead of pixels.Use the below code to get measurement in dp of sample width=300px and height=400px.
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
int Height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, getResources().getDisplayMetrics());
float dps = 100;
float pxs = dps * getResources().getDisplayMetrics().density;
Source (#Romain Guy)
Based on above answers which works fine to me, i generate some helper methods, just add them in your utils to use them in whole project.
// value in DP
public static int getValueInDP(Context context, int value){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
}
public static float getValueInDP(Context context, float value){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
}
// value in PX
public static int getValueInPixel(Context context, int value){
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
}
public static float getValueInPixel(Context context, float value){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, value, context.getResources().getDisplayMetrics());
}
It uses pixels. here's a Kotlin extension function to convert pixels to dp
fun Context.pxToDp(value: Float):Int{
val r: Resources = resources
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, value, r.displayMetrics
).roundToInt()
}
Pixels of course, the method is asking for pixels as parameter.

Categories

Resources