Texto de Android alrededor de error de imagen

Siguiendo esta pregunta , pude tener texto alrededor de una imagen. Sin embargo, tengo el siguiente problema.

Introduzca aquí la descripción de la imagen

Como puede ver, el espacio para la imagen en la parte superior se muestra en cada párrafo a la derecha. En la pregunta alguien tenía este problema y sugirió cambiar 'ss.length ()' para 'lines'. Esto parecía funcionar, excepto si el primer párrafo era demasiado corto, el próximo párrafo se superpondría a la imagen.

Modifiqué ligeramente la clase de FlowTextHelper para utilizar el texto de Html. Este es el código que estoy usando:

public class FlowTextHelper { private static boolean mNewClassAvailable; /* class initialization fails when this throws an exception */ static { try { Class.forName("android.text.style.LeadingMarginSpan$LeadingMarginSpan2"); mNewClassAvailable = true; } catch (Exception ex) { mNewClassAvailable = false; } } public static void tryFlowText(String text, View thumbnailView, TextView messageView, Display display, int addPadding){ // There is nothing I can do for older versions, so just return if(!mNewClassAvailable) return; // Get height and width of the image and height of the text line thumbnailView.measure(display.getWidth(), display.getHeight()); int height = thumbnailView.getMeasuredHeight(); int width = thumbnailView.getMeasuredWidth() + addPadding; messageView.measure(width, height); //to allow getTotalPaddingTop int padding = messageView.getTotalPaddingTop(); float textLineHeight = messageView.getPaint().getTextSize(); // Set the span according to the number of lines and width of the image int lines = (int)Math.round((height - padding) / textLineHeight); //SpannableString ss = new SpannableString(text); //For an html text you can use this line: if(!text.equals("")) { SpannableStringBuilder ss = (SpannableStringBuilder) Html.fromHtml(text); ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), 0); messageView.setText(ss); messageView.setMovementMethod(LinkMovementMethod.getInstance()); // links // Align the text with the image by removing the rule that the text is to the right of the image RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) messageView.getLayoutParams(); int[] rules = params.getRules(); rules[RelativeLayout.RIGHT_OF] = 0; } } } public class MyLeadingMarginSpan2 implements LeadingMarginSpan.LeadingMarginSpan2 { private int margin; private int lines; public MyLeadingMarginSpan2(int lines, int margin) { this.margin = margin; this.lines = lines; } @Override public int getLeadingMargin(boolean first) { return first ? margin : 0; } @Override public int getLeadingMarginLineCount() { return lines; } @Override public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) {} } 

¿Qué está causando que el espacio se repita cada párrafo y cómo puedo deshacerme de él? Cualquier ayuda es apreciada.

He pasado horas para resolver este problema, pero lo resolví gracias a la respuesta que encontré aquí: texto que envuelve alrededor de la imagen en android

Básicamente como sigue:

Primero agregue un margen a su texto y configure el texto

 final RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams)messageView.getLayoutParams(); params.setMargins(marginWidth, 0, 0, 0); messageView.setText(Html.fromHtml(text)); 

A continuación, agregue un OnGlobalLayoutListener y en la llamada onGlobalLayout () calculará cuántas líneas realmente necesitan el margen. Usted divide las líneas en 2 spannables separados y agregue el margen solamente a la primera:

  messageView.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @SuppressLint("NewApi") @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { int linesCount = messageView.getLayout().getLineCount(); // restore the margin params.setMargins(0, 0, 0, 0); SpannableString spanS = new SpannableString ( Html.fromHtml(text) ); if (linesCount <= lines) { spanS.setSpan(new MyLeadingMarginSpan2(lines, width), 0, spanS.length(), 0); messageView.setText(spanS); } else { // find the breakpoint where to break the String. int breakpoint = messageView.getLayout().getLineEnd(lines-1); Spannable s1 = new SpannableStringBuilder(spanS, 0, breakpoint); s1.setSpan(new MyLeadingMarginSpan2(lines, width), 0, s1.length(), 0); Spannable s2 = new SpannableStringBuilder(System.getProperty("line.separator")); Spannable s3 = new SpannableStringBuilder(spanS, breakpoint, spanS.length()); // It is needed to set a zero-margin span on for the text under the image to prevent the space on the right! s3.setSpan(new MyLeadingMarginSpan2(0, 0), 0, s3.length(), 0); messageView.setText(TextUtils.concat(s1, s2, s3)); } // remove the GlobalLayoutListener if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { messageView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { messageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } } }); 

Si necesita ajustar texto alrededor de una imagen, utilice esta biblioteca FlowTextView .

La biblioteca funciona bien, y se puede utilizar con un par de líneas. Sin embargo, no admite el tamaño de píxel de pantalla para las fuentes. He encontrado una solución con esta respuesta , para que pueda convertir tamaño de píxel a sp.

Espero que esto ayude a cualquiera y no pierdas tanto tiempo como yo usando la pregunta de mi post original.

  • Vista de texto con textos de colores diferentes en código xml
  • Desplazamiento por programación de una palabra en vista en una vista de texto
  • Android setError ("error") no funciona en Textview
  • Verdaderamente el texto de alineación superior en Android TextView
  • TextView: Trácese sin respetar espacios entre palabras
  • Extra padding en TextView con contenido HTML
  • Hifenización en Android
  • Horizontalmente Scrollable TextView mostrar el comportamiento inconsistente en las versiones de Android
  • Android Html.fromHtml función automática convierte texto no deseado en hipervínculos
  • Android - epub reader para leer archivos .epub ..
  • Superposición de texto sobre la vista de imagen en android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.