Multilínea de Android TextView, comprueba si el texto se ajusta o comprueba si TextView está lleno
Tengo un diseño de aplicación de Android que contiene una multilínea TextView. Cuando la pantalla está en orientación vertical, TextView puede mostrar una longitud diferente de texto cuando se ejecuta en modo horizontal. También cuando se ejecuta en una pantalla pequeña, TextView puede mostrar una longitud diferente de texto para cuando se ejecuta en una pantalla más grande.
¿Hay alguna manera de comprobar si el texto se ajusta o se truncar? ¿O hay alguna manera de comprobar si el TextView está lleno?
- Cambio de texto de TextView: el texto antiguo no desaparece (Android 4.1.2)
- Establecer desvanecimiento de texto en Android 4.0.3
- ¿Hay una manera de comprobar si el texto de TextView está truncado
- ¿Qué se entiende por Ems? (Android TextView)
- ¿Cómo puedo cambiar el color del textView android.R.layout.simple_spinner_dropdown_item?
El problema es que TextView puede contener un número diferente de líneas, dependiendo de si es paisaje, retrato, pantalla pequeña, pantalla grande, etc.
Gracias por tu consejo,
Atentamente,
James
- ¿Cómo obtener el recuento de líneas de textview antes de renderizar?
- Cómo ampliar una vista de texto en android?
- TextView en el centro de la pantalla
- Cómo eliminar Android auto-sugiere subrayar en EditText?
- Android: textisselectable no funciona en la ventana TYPE_SYSTEM_ALERT
- Abrir vínculos de TextView en otra actividad, no en el navegador predeterminado
- Cómo obtener el ancho de textView en android
- NSString: sizeWithFont: forWidth: lineBreakMode Android equivalente
Estas respuestas no funcionaron muy bien para mí. Esto es lo que terminé haciendo
Paint measurePaint = new Paint(myTextView.getPaint()); float pWidth = measurePaint.measureText("This is my big long line of text. Will it fit in here?"); float labelWidth = myTextView.getWidth(); int maxLines = myTextView.getMaxLines(); while (labelWidth > 0 && pWidth/maxLines > labelWidth-20) { float textSize = measurePaint.getTextSize(); measurePaint.setTextSize(textSize-1); pWidth = measurePaint.measureText("This is my big long line of text. Will it fit in here?"); if (textSize < TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 7, getContext().getResources().getDisplayMetrics())) break; } myTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, measurePaint.getTextSize());
No estoy diciendo que esto funcione para cada situación como estoy ciertamente cortando esquinas aquí, pero la idea general es medir el texto con la pintura del textview y guardar el encogerse hasta que cabrá dentro del textview.
He encontrado una solución "descarada" al problema de medir la altura del texto en un MULTILINE TextView :
//Calculate the height of the text in the MULTILINE TextView int textHeight = textView.getLineCount() * textView.getLineHeight(); if (textHeight > textViewHeight) { //Text is truncated because text height is taller than TextView height } else { //Text not truncated because text height not taller than TextView height }
Sin embargo esta solución tiene algunas advertencias: –
En primer lugar con respecto a getLineHeight (), el marcado dentro del texto puede hacer que las líneas individuales sean más altas o más cortas que esta altura, y el diseño puede contener relleno adicional de primera o última línea. Consulte http://developer.android.com/reference/android/widget/TextView.html#getLineHeight ()
En segundo lugar, la aplicación debe calcular la altura real del TextView en píxeles y (en el caso de mi diseño) puede no ser tan simple como textView.getHeight (), y el cálculo puede variar de un diseño a otro.
Recomendaría evitar LinearLayout porque la altura real de píxel de TextView puede variar dependiendo del contenido del texto. Estoy usando un RelativeLayout (vea http://pastebin.com/KPzw5LYd ).
Usando este RelativeLayout, puedo calcular mi altura de TextView como sigue: –
//Calculate the height of the TextView for layout "http://pastebin.com/KPzw5LYd" int textViewHeight = layout1.getHeight() - button1.getHeight() - button2.getHeight();
Espero que ayude,
Saludos,
James
Básicamente, usted necesita calcular el tamaño de su textview y el tamaño de su texto cuando el modo de la orientación cambió. Intente ViewTreeObserver.OnGlobalLayoutListener
para hacerlo.
Dentro del método de orientación del cambio:
main_view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { main_view.getViewTreeObserver().removeGlobalOnLayoutListener(this); //Calculation goes here int text_size = getTextSize(text_view.getText().toString()); int text_view_size = text_view.getLayoutParams().width; //Compare your text_size and text_view_size and do whatever you want here. } });
Aquí está el código de calcular el text_size:
private int getTextSize(String your_text){ Paint p = new Paint(); //Calculate the text size in pixel return p.measureText(your_text); }
Espero que esto ayude.
Para comprobar si una multilínea (o no) TextView va a ser truncado, compruebe esta publicación .
¿O, usted miró adentro usando una vista de texto de desplazamiento? (Marquesina) .. donde el texto se desplazará por (horizontalmente, animado) si es demasiado largo para un ancho dado?
Aquí hay un ejemplo de TextView en un archivo de diseño, que tiene algunas de estas características:
<TextView android:id="@+id/sometextview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:singleLine="true" android:scrollHorizontally="true" android:focusable="true" android:focusableInTouchMode="true" android:freezesText="true" android:textColor="#808080" android:textSize="14sp" android:text="This is a long scrolling line of text.. (etc)"/>
- ¿Es necesario llamar a Bitmap.recycle () después de usarlo (en Android)?
- Java.lang.illegalstateexception: ya se ha establecido una fábrica en este layoutinflater