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.
¿Por qué no puedes simplemente usar 'android: width = WRAP_CONTENT' en XML? –
eliminar el atributo maxWidth y probar – Thamilvanan
>> ¿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. –