I made an application that is a form, and I did everything via code without using xml, so my textViews and Edittexts stayed in pixels.
On the tablet it works fine, but on the mobile with a lower resolution, everything is "encavalado".
I made an application that is a form, and I did everything via code without using xml, so my textViews and Edittexts stayed in pixels.
On the tablet it works fine, but on the mobile with a lower resolution, everything is "encavalado".
In order for the dimensions to remain consistent across the various screen types, you should think in terms of DP and not pixel.
As most (I would say all but I'm not sure) the methods that use dimensions are expressed in pixels should convert the dps into pixels.
To do this you can use the following method:
public static int convertDpToPixels(float dp, Activity context){
DisplayMetrics metrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
return (int) Math.ceil(dp * density);
}
Try something like this:
public static int converteDpParaPx(Context context, int dps) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, displayMetrics));
}
I use an auxiliary class to work with unit conversions.
package com.example;
import android.content.res.Resources;
public class UnityConverter {
private static float scaleFactor = 1;
private UnityConverter() {
}
/**
* Configura o conversor de acordo com o device do usuário.
*
* @param res
* os resources da aplicação
*/
public static void config(Resources res) {
scaleFactor = res.getDisplayMetrics().density;
}
/**
* Converte um valor numerico para a unidade dp sem arredondamento
*
* @param value
* o valor a ser convertido
* @return o valor em dp's
*/
public static float toDp(float value) {
return value * scaleFactor;
}
/**
* Converte um valor numerico para a unidade dp sem arredondamento
*
* @param value
* o valor a ser convertido
* @return o valor em dp's
*/
public static float toDp(int value) {
return value * scaleFactor;
}
/**
* Converte um valor numerico para a unidade dp arredondado
*
* @param value
* o valor a ser convertido
* @return o valor em dp's
*/
public static int toRoundDp(float value) {
return (int) (value * scaleFactor);
}
/**
* Converte um valor numerico para a unidade dp arredondado
*
* @param value
* o valor a ser convertido
* @return o valor em dp's
*/
public static int toRoundDp(int value) {
return (int) (value * scaleFactor);
}
}
Use
UnityConverter.config(getResources());
int dp = UnityConverter.toRoundDp(120)