2012-06-06 16 views
9

¿Cómo puedo hacer que la vista de texto ajuste ese texto exactamente?
¿Cómo hacer que textView envuelva su contenido multilínea exactamente?

android: el atributo de ancho no es una solución, porque el texto es dinámico.

comportamiento deseado

|Adcs | 
|adscfd| 

behavour actual:

|Adcs  | 
|adscfd | 

Hereis el código (estilos de TextViews sólo definen cosas como textColor, TEXTSIZE, TEXTSTYLE).

<TextView 
     android:id="@+id/text_title_holder" 
     style="@style/TextBold.Black.Title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:maxWidth="100dp" 
     android:maxLines="2" 
     android:text="Adcs adscfd" 
     android:gravity="left" 
     android:visibility="visible" /> 

El tema wrap_content width on mutiline TextView no tiene una respuesta buena.

+0

¿Por qué no puedes simplemente usar 'android: width = WRAP_CONTENT' en XML? –

+0

eliminar el atributo maxWidth y probar – Thamilvanan

+0

>> ¿Por qué no puedes simplemente usar android: width = WRAP_CONTENT android: el atributo width no acepta el parámetro "wrap_content". Solo acepta valores numéricos. –

Respuesta

12

Me he enfrentado a este problema y no encontré la solución en Internet. Hice este truco creando el nuevo componente TightTextView que vuelve a medir el texto dado en caso de que haya especificado el maxWidth del componente y el ancho de Layout (del texto) es menor que el ancho medido de la vista.

package com.client.android.app.views; 

import android.content.Context; 
import android.text.Layout; 
import android.util.AttributeSet; 
import android.widget.TextView; 

/** 
* Tightly wraps the text when setting the maxWidth. 
* @author sky 
*/ 
public class TightTextView extends TextView { 
    private boolean hasMaxWidth; 

    public TightTextView(Context context) { 
     this(context, null, 0); 
    } 

    public TightTextView(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public TightTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 

     if (hasMaxWidth) { 
      int specModeW = MeasureSpec.getMode(widthMeasureSpec); 
      if (specModeW != MeasureSpec.EXACTLY) { 
       Layout layout = getLayout(); 
       int linesCount = layout.getLineCount(); 
       if (linesCount > 1) { 
        float textRealMaxWidth = 0; 
        for (int n = 0; n < linesCount; ++n) { 
         textRealMaxWidth = Math.max(textRealMaxWidth, layout.getLineWidth(n)); 
        } 
        int w = Math.round(textRealMaxWidth); 
        if (w < getMeasuredWidth()) { 
         super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST), 
           heightMeasureSpec); 
        } 
       } 
      } 
     } 
    } 


    @Override 
    public void setMaxWidth(int maxpixels) { 
     super.setMaxWidth(maxpixels); 
     hasMaxWidth = true; 
    } 

    @Override 
    public void setMaxEms(int maxems) { 
     super.setMaxEms(maxems); 
     hasMaxWidth = true; 
    } 
} 

!!! Acabo de portarlo a las API de Android anteriores, cuz getMaxWidth() solo está disponible desde el nivel 16 de la API.

+0

+1, esto funcionó y debería ser la respuesta aceptada – h4lc0n

+1

Estoy confundido acerca de por qué el material de maxWidth aquí es necesario. Con él, este código no me solucionó el problema. Una vez que lo saqué, funcionó. –

+1

Tengo una causa de Math.round(). El último carácter de la línea más grande está recortado. Reemplazando Math.round() con FloatMath.ceil() resolvió el problema. – HighFlyer

1

Esta pregunta es un poco antigua pero también tuve este problema donde quería texto verde en un recuadro negro sobre un mapaVer y solucioné poniendo mi textView en un contenedor RelativeLayout. Luego usé relleno para establecer el tamaño del borde. El textView ahora abraza el texto muy bien. Mi contorno en eclipse se ve así.

RelativeLayout 
    mapview 
    LinearLayout 
     RelativeLayout 
      textView1 << this is the box I want to hug the text 
     imageView1 
    RelativeLayout 
    etc.... 

Espero que esto ayude.

+0

¿Alguna vez encontró una solución a este problema? – Uxonith

Cuestiones relacionadas