Work with dp on Android

11

My question I think should be simple to answer, but I really do not know the answer so it goes there:

I am trying to subtract the original height of a layout 50 dps . Right now I do it in the following way:

v.getLayoutParams().height = initialHeight -  50;
v.requestLayout();

The problem with this is that you are subtracting through the metric px , and I would like to work with dp

    
asked by Mario López Batres 20.01.2017 в 21:57
source

4 answers

17

You can convert from dp to pixels in the following way:

// tu cálculo del valor en dp
final float alturaDp = initialHeight - 50;

// Obtener la densidad de pantalla
final float escala = getResources().getDisplayMetrics().density;
// Convertir los dps a pixels, basado en la escala de densidad
alturaPx = (int) (alturaDp * escala + 0.5f);

Original source in the official documentation available in Spanish

As the answer so far did not seem useful, so that it is understood:

You can not work with dp in LayoutParams . Internally, classes work with pixels. So the only way to work with values in dp is to convert them to pixels and then apply the pixels.

    
answered by 20.01.2017 / 22:32
source
4

Another alternative is to define the dp unit in the dimens.xml

file
<dimen name="resta_height">50dp</dimen> 

and in your code put:

v.getLayoutParams().height = initialHeight - (int)getResources().getDimension(R.dimen.resta_height);

source

    
answered by 16.02.2017 в 21:16
3

The correct way is described in the source code of Android:

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

by Romain Guy who was working with Android in its inception.

This is also described in the documentation: Conversion of dp units into pixel units .

// El umbral gestual expresado en dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;

//Obtener la escala de densidad de la pantalla.
final float scale = getResources().getDisplayMetrics().density;
// Convertir el dps en píxeles, basado en la escala de densidad
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);

// Usar mGestureThreshold como una distancia en píxeles...

Method to convert dp to pixels.

public int getPixelsfromDP(Context ctx, float dps) {
      float scale = ctx.getResources().getDisplayMetrics().density;
      return (int) (dps * scale + 0.5f);
}
    
answered by 22.02.2017 в 21:51
1

You should convert the 50dp you want to pixels and then subtract these pixels at the height of the view. The number of pixels will be different depending on the pixel density of the device.

Resources r = getResources();
float pixels = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics());

v.getLayoutParams().height = initialHeight - pixels;
v.requestLayout();
    
answered by 23.02.2017 в 14:52