studio fromhtml example android textview html-parsing spanned

studio - html.fromhtml android example



Imágenes de Android ImageGetter que se superponen texto (5)

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 ningún espacio creado para que puedan sentarse, por lo que terminan superponiéndose con el texto sobre ellas. 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 particular por la que deba cargarlo en una vista de texto? ¿Podrías usar un WebView lugar?

Si no puede usar Webviews, la mejor solución es no colocar las imágenes en su vista de texto. Ponga las imágenes en un ImageView. TextViews no tiene ninguna de las capacidades del motor de diseño que necesita para averiguar dónde colocar las imágenes y los textos entre sí. No son grupos de vistas (como LinearLayout o RelativeLayout) y, por lo tanto, no tienen capacidades internas de especificación de diseño. Si realmente no quieres usar una vista web (y todo lo que tiene de motor de diseño agradable), tendrás que averiguar cómo organizar las vistas de texto individuales y las vistas de imagen.


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

Para resolver este problema, había convertido el ImageGetter de la AsyncTask y, en su lugar, inicié una AsyncTask que crea el Spanned para mi TextView y luego establece el texto.

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);


Es posible que no necesitemos 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(); }


No tengo la reputación suficiente para votar por Martin S, pero su respuesta es muy útil. Y si TextView muestra 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()));


Podría cambiar su cointainer c (ver) a un textView y luego hacer que su onPostExecute se vea así:

@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 y luego establecerá inmediatamente la altura de TextView a la altura del dibujable + la altura de TextViews