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?

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

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)"/> 
  • Cómo deshabilitar el TextView maxLines mediante programación?
  • Android Paint: .measureText () vs .getTextBounds ()
  • Android TextView Problema de enfoque en listview (sólo MarshMallow)
  • Poner una vista de texto encima de un fragmento de lista
  • El tamaño de fuente diferente de las cadenas en el mismo TextView
  • Aplicación de la transformación después de la animación de rotación de textview en Android
  • Cómo obtener atributos con el espacio de nombres "android" en TextView personalizado
  • Android - ¿Por qué autolink ignora la ruta raíz de una URL?
  • Barra de acción de corte / copia personalizada para EditText que muestra las manijas de selección de texto
  • Android textview relleno entre líneas
  • Dibujar línea a través de texto en textview
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.