Imágenes de ImageGetter de Android superpuestas al texto

Estoy tratando de cargar un bloque de HTML en un TextView, incluyendo imágenes, usando

URLImageParser p = new URLImageParser(articleBody, this); Spanned htmlSpan = Html.fromHtml(parsedString, p, null); 

ParsedString es el HTML, por cierto. De todos modos, se carga, pero las imágenes no tienen espacio creado para sentarse, por lo que terminan superponiendo el texto por encima de ellos. Aquí está mi archivo URLImageParser:

 public class URLImageParser implements Html.ImageGetter { Context c; View container; /*** * Construct the URLImageParser which will execute AsyncTask and refresh the container * @param t * @param c */ public URLImageParser(View t, Context c) { this.c = c; this.container = t; } public Drawable getDrawable(String source) { URLDrawable urlDrawable = new URLDrawable(); // get the actual source ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask( urlDrawable); asyncTask.execute(source); // return reference to URLDrawable where I will change with actual image from // the src tag return urlDrawable; } public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> { URLDrawable urlDrawable; public ImageGetterAsyncTask(URLDrawable d) { this.urlDrawable = d; } @Override protected Drawable doInBackground(String... params) { String source = params[0]; return fetchDrawable(source); } @Override protected void onPostExecute(Drawable result) { // set the correct bound according to the result from HTTP call Log.d("height",""+result.getIntrinsicHeight()); Log.d("width",""+result.getIntrinsicWidth()); urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 0+result.getIntrinsicHeight()); // change the reference of the current drawable to the result // from the HTTP call urlDrawable.drawable = result; // redraw the image by invalidating the container URLImageParser.this.container.invalidate(); } /*** * Get the Drawable from URL * @param urlString * @return */ public Drawable fetchDrawable(String urlString) { try { URL aURL = new URL(urlString); final URLConnection conn = aURL.openConnection(); conn.connect(); final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); final Bitmap bm = BitmapFactory.decodeStream(bis); Drawable drawable = new BitmapDrawable(bm); drawable.setBounds(0,0,bm.getWidth(),bm.getHeight()); return drawable; } catch (Exception e) { return null; } } } 

}

¿Algunas ideas? Gracias una tonelada.

¿Hay alguna razón en particular que necesite para cargarla en una vista de texto? ¿Podrías usar un WebView en su lugar?

Si no puede utilizar Webviews, entonces la mejor solución es no colocar las imágenes en su vista de texto. Coloque las imágenes en un ImageView. TextViews no tiene ninguna de las capacidades del motor de diseño que necesita para determinar dónde colocar imágenes y textos en relación entre sí. No son ViewGroups (como LinearLayout o RelativeLayout) y, por lo tanto, no tienen capacidades de especificación de diseño interno. Si realmente no quieres usar una webview (y todas las cosas de ingeniería de diseño agradable que tiene), vas a tener que averiguar cómo organizar TextViews individuales y ImageViews usted mismo.

Usted podría cambiar su cointainer c (ver) a un textView y luego hacer su onPostExecute parecerse a esto:

 @Override protected void onPostExecute(Drawable result) { // set the correct bound according to the result from HTTP call Log.d("height",""+result.getIntrinsicHeight()); Log.d("width",""+result.getIntrinsicWidth()); urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 0+result.getIntrinsicHeight()); // change the reference of the current drawable to the result // from the HTTP call urlDrawable.drawable = result; // redraw the image by invalidating the container URLImageParser.this.container.invalidate(); // For ICS URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight() + result.getIntrinsicHeight())); // Pre ICS URLImageParser.this.textView.setEllipsize(null); } 

Esto primero dibujará la imagen e inmediatamente fijará la altura del TextView a la altura del dibujable + la altura de TextViews

No tengo suficiente reputación para votar por Martin S, pero su respuesta es muy útil. Y si TextView ha mostrado una imagen predeterminada antes de cargar, podemos cambiar el método setHeight () de esta manera:

  URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight() + result.getIntrinsicHeight()-mDefaultDrawable.getInstrinsicHeight())); 

Puede ser que no es necesario cambiar el contenedor de Vista a TextView.

  @Override protected void onPostExecute(Drawable result) { // set the correct bound according to the result from HTTP call urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0 + result.getIntrinsicHeight()); // change the reference of the current drawable to the result // from the HTTP call urlDrawable.drawable = result; // redraw the image by invalidating the container URLImageParser.this.container.setMinimumHeight((URLImageParser.this.container.getHeight()+ result.getIntrinsicHeight())); URLImageParser.this.container.requestLayout(); URLImageParser.this.container.invalidate(); } 

Encontré un comportamiento interesante con esas soluciones: si la carga de una imagen es rápida y la vista de texto no se ha procesado todavía (por ejemplo, uso Okhttp con almacenamiento en caché, por lo que la segunda llamada es bastante rápida), el tamaño de vista de texto es 0.

Para resolver este problema, había convertido el ImageGetter de AsyncTask y en su lugar iniciar un AsyncTask que crea el Spanned para mi TextView y establece el texto después.

Con esta solución no es necesario cambiar el tamaño de TextView cada vez que se carga una imagen.

 new AsyncTask<TextView, Void, Spanned>() { TextView tv; @Override protected Spanned doInBackground(TextView... params) { tv = params[0]; return Html.fromHtml(feedEntry.getContent(), new HttpImageGetter(getActivity(), HttpLoaderImpl.getInstance(getActivity())), new Html.TagHandler() { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { //do nothing... } }); } @Override protected void onPostExecute(final Spanned result) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { tv.setText(result); } }); } }.execute(textView); 
  • Disposición de Android: Alinear un TextView y un Spinner
  • TextView ampliar animación como en Android Market
  • TextView: Trácese sin respetar espacios entre palabras
  • Obtener texto vinculado de textview-android ...?
  • Nuevo carácter de línea \ n no se muestra correctamente en textView Android
  • ¿Cómo inserto un salto de línea en una cadena para mostrarlo en un widget Android TextView?
  • El salto de línea en Android agrega relleno
  • Leftside de texto de un RadioButton con un margen en Android
  • ¿Cómo solucionar este error en Android? Java.net.MalformedURLException: Protocolo no encontrado:
  • Hacer que los elementos de ListView sean seleccionables
  • Cómo alinear TextView alrededor de un ImageView?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.