1

Estoy batellando que algunas lineas de un TextView se pueda alinear a la izquierda, derecha o centro.

Entiendo que se debe realizar con SpannableString y su alineación AlignmentSpan.Standard(Layout.Alignment...)

  • ALIGN_NORMAL
  • ALIGN_CENTER
  • ALIGN_OPPOSITE

Dejo parte del banco de pruebas

String str1 = "linea justificada a la izquierda";
String str2 = "linea centrada";
String str3 = "linea justificada a la derecha"

TextView tv = (TextView) findViewById(R.id.debug_log);

tv.append(...)

¿Cómo se implementa un SpannableString con su alineación?

2 respuestas 2

5

Puedes emplear el siguiente método

 appendText(str1, Layout.Alignment.ALIGN_NORMAL);
 appendText(str2, Layout.Alignment.ALIGN_CENTER);
 appendText(str3, Layout.Alignment.ALIGN_OPPOSITE);

private void appendText(CharSequence text, Layout.Alignment align) {
    if (text == null || text.toString().trim().length() == 0) {
        return;
    }

    AlignmentSpan span = new AlignmentSpan.Standard(align);
    SpannableString spannableString = new SpannableString(text);
    spannableString.setSpan(span, 0, text.length(), 0);

    tvPruebas = (TextView) findViewById(R.id.pruebas);

    if (tvPruebas.length() > 0) {
        tvPruebas.append("\n\n");
    }
    tvPruebas.append(spannableString);
}

y obtienes el siguiente resultado:

introducir la descripción de la imagen aquí

3
  • y donde se carga tvPruebas con findViewById etc..
    – Codelaby
    el 29 jun. 2016 a las 16:34
  • 1
    tvPruebas = (TextView) findViewById(R.id.pruebas);
    – Bourne
    el 29 jun. 2016 a las 16:38
  • Me refiero, es lo que le falta al código
    – Codelaby
    el 29 jun. 2016 a las 16:39
2

Basandome con la respuesta de @Bourne he modificado su solución, para así puede usarse en cualquier TextView que tengamos en la App.

Función appendTextAlignment

private void appendTexAlignment(final TextView tv, Layout.Alignment align, CharSequence text) {
    if (text == null || text.toString().trim().length() == 0) { return; }

    AlignmentSpan span = new AlignmentSpan.Standard(align);
    SpannableString spannableString = new SpannableString(text);
    spannableString.setSpan(span, 0, text.length(), 0);

    if (tv != null) {
        tv.append(spannableString);
    }
}

Su uso

TextView tv = (TextView) findViewById(R.id.debug_log);

appendTextAlignment(tv,Layout.Alignment.ALIGN_NORMAL,"Izquierda\n");
appendTextAlignment(tv,Layout.Alignment.ALIGN_CENTER,"Centrado\n");
appendTextAlignment(tv,Layout.Alignment.ALIGN_OPPOSITE,"Derecha\n");

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.