Cómo asignar el tamaño del texto en el valor sp usando código java


Si asignoun valor entero para cambiar un cierto tamaño de texto de TextView usando código java, el valor se interpreta como píxel (px). Ahora, ¿alguien sabe cómo asignarlo en sp?

Author: Hussein El Feky, 2010-01-15

11 answers

 458
Author: Santosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-11 17:02:49

Puede utilizar un DisplayMetrics objeto para ayudar a convertir entre píxeles y píxeles escalados con el scaledDensity atributo.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
 34
Author: Dave Webb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-15 06:42:32

Un enfoque más limpio y reutilizable es

Defina el tamaño del texto en el archivo dimens.xml dentro del directorio res/values/:

</resources>
   <dimen name="text_medium">14sp</dimen>
</resources>

Y luego aplicarlo a la TextView:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));
 23
Author: klimat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-15 10:15:10

Basado en el código fuente de setTextSize:

public void setTextSize(int unit, float size) {
    Context c = getContext();
    Resources r;

    if (c == null)
        r = Resources.getSystem();
    else
        r = c.getResources();

    setRawTextSize(TypedValue.applyDimension(
        unit, size, r.getDisplayMetrics()));
}

Construyo esta función para calcular cualquier demensión a píxeles:

int getPixels(int unit, float size) {
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    return (int)TypedValue.applyDimension(unit, size, metrics);
}

Donde la unidad es algo así como TypedValue.COMPLEX_UNIT_SP.

 18
Author: rekire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-26 06:50:19

Por defecto setTextSize, sin unidades trabajan en SP (escala pixel)

public void setTextSize (float size) 
Added in API level 1
Set the default text size to the given value, interpreted as "scaled pixel" units. This 
size is adjusted based on the current density and user font size preference.
 12
Author: Zeus Monolitics,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-11 23:20:49

Gracias @ John Leehey y @ PeterH:

desiredSp = getResources().getDimension(R.dimen.desired_sp);
density = getResources().getDisplayMetrics().density;
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, desiredSp / density);

La cosa es si defines R. dimen.desired_sp a 25 en su dimensión.xml

  1. En dispositivos no HD: desiredSp sigue siendo 25, densidad = 1
  2. En dispositivos HD (como Nexus 7 2nd Generation): desiredSp se convierte en 50 ish, densidad = 2
 10
Author: macio.Jun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-30 15:07:37

Cuando la respuesta aceptada no funciona (por ejemplo, cuando se trata de pintura) se puede utilizar:

float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);
 8
Author: pomber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-03 13:32:20
semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                       context.getResources().getDimension(R.dimen.text_size_in_dp))
 7
Author: William Hu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-20 09:50:00

Este es el código para convertir PX a SP formato. 100% Funciona

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
 2
Author: Kamran Qasimov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 16:53:22

Después de probar todas las soluciones y ninguna dando resultados aceptables (tal vez porque estaba trabajando en un dispositivo con fuentes predeterminadas muy grandes), lo siguiente funcionó para mí (COMPLEX_UNIT_DIP = Device Independent Pixels):

textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
 0
Author: tsig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 14:35:38

En caso de que alguien esté buscando Kotlin way, puede hacer

view.textSize = 12f
 -1
Author: Nari Kim Shin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-03 23:46:57