android-TextView setText in Html.fromHtml to display image and text
This is the coding for reference to user pskink...
package com.tutorial.myjob;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.text.*;
import android.text.Html.ImageGetter;
import android.widget.*;
public class HelpMenu extends Activity implements ImageGetter{
TextView message;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_menu);
String code = "<p><b>First, </b><br/>" +
"Please press the <img src ='addbutton.png'> button beside the to insert a new event.</p>" +
"<p><b>Second,</b><br/>" +
"Please insert the details of the event.</p>"
"<p>The icon of the is show the level of the event.<br/>" +
"eg: <img src = 'tu1.png' > is easier to do.</p></td>";
message = (TextView) findViewById (R.id.message);
Spanned spanned = Html.fromHtml(code, this, null);
message.setText(spanned);
message.setTextSize(16);
}
@Override
public Drawable getDrawable(String arg0) {
// TODO Auto-generated method stub
int id = 0;
if(arg0.equals("addbutton.png")){
id = R.drawable.addbutton;
}
if(arg0.equals("tu1.png")){
id = R.drawable.tu1;
}
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(id);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
return d;
}
}
This is what I edit... These coding run well for me... Thanks a lot for those helping me... Appreciated~ ^^
How to display HTML in TextView?
You need to use Html.fromHtml()
to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.
This is what you should do in Java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}
And in Kotlin:
textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(html)
}
Visualizing an image from Html.fromHtml in a TextView(The image must be in the server)
The method Html.fromHtml
supports loading of <img>
tags, however you're going to need to manage the way the images are fetched yourself.
Remember, this is not a web client... this is an Android app. The fromHtml
method is really a method which interprets some html tags, and creates appropriate Spannables
which best fit the html tags.
And so, we're back the the issue with the images (img
tags). Again, this is not a web client. You're going to need to load the images yourself.
To do this, you need to pass to the fromHtml
method an ImageGetter
implementing class. See example for how to implement an ImageGetter
here.
Short version - you'll need to implement a method which accepts a string of the asset name, and returns a Drawable
object. This method needs to be synchronous, which means you're going to need to pre-load all the image files from the server before-hand and have them ready to load when you call fromHtml
.
How to display HTML img tag inside Android TextView
You should use WebView
instead of TextView
WebView = findViewById(R.id.WebView);
WebView.loadData(source, "text/html", "utf-8");
You will get the same output.
Show image in textview using Html.fromhtml();
You can draw an Image
in TextView
using the Html
img tag
with Html.ImageGetter
. But make sure your image is available in resource drawable
folder
Here is a sample , The image will be loaded from the resource.
String htmlText = "Hai <img src=\"ic_launcher\"> Hello";
textView.setText(Html.fromHtml(htmlText, new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int resourceId = getResources().getIdentifier(source, "drawable",getPackageName());
Drawable drawable = getResources().getDrawable(resourceId);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
}, null));
Cannot display images in Html.fromHtml() in text view for images coming dynamically
I also faced a similar problem month ago and used this and it works fine :
String htmlData = listData.get(position).getValue();
String showData = htmlData.replace("\n", "");
URLImageParser p = new URLImageParser(holder.textt, context);
Spanned htmlAsSpanned = Html.fromHtml(showData,p,null);
holder.yourTextView.setText(htmlAsSpanned);
Now copy and paste these 2 methods :
First method :
public class URLDrawable extends BitmapDrawable {
protected Drawable drawable;
@Override
public void draw(Canvas canvas) {
if(drawable != null) {
drawable.draw(canvas);
}
}
}
///Second Method :
public class URLImageParser implements Html.ImageGetter {
Context c;
TextView container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* @param t
* @param c
*/
public URLImageParser(TextView 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
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();
URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));
}
/***
* Get the Drawable from URL
* @param urlString
* @return
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} `enter code here`catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
Show image from HTML tag in text view?
You can use this code for set html image and text both from textview:
This is xml code:
<TextView
android:id="@+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:lineSpacingExtra="5dp"
android:padding="5dp"
android:textAppearance="@style/TextAppearance.AppCompat.Small"
android:textColor="@color/black" />
This is Java code:
public class ConditionOfUseActivity extends Activity implements Html.ImageGetter {
private TextView txtDescription;
private Drawable empty;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_condition_use);
txtDescription = (TextView) findViewById(R.id.txtDescription);
String source = "this is a test of <b>ImageGetter</b> it contains " +
"two images: <br/>" +
"<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" +
"<img src=\"http://developer.android.com/assets/images/icon_search.png\">";
Spanned spanned = Html.fromHtml(object.getString("content"), ConditionOfUseActivity.this, null);
txtDescription.setText(spanned);
}
@Override
public Drawable getDrawable(String s) {
LevelListDrawable d = new LevelListDrawable();
empty = getResources().getDrawable(R.drawable.splash1);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(s, d);
return d;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
private LevelListDrawable mDrawable;
@Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(bitmap);
mDrawable.addLevel(1, 1, d);
//mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
mDrawable.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
mDrawable.setLevel(1);
CharSequence t = txtDescription.getText();
txtDescription.setText(t);
}
}
}
Is it possible to display inline images from html in an Android TextView?
If you have a look at the documentation for Html.fromHtml(text)
you'll see it says:
Any
<img>
tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.
If you don't want to do this replacement yourself you can use the other Html.fromHtml()
method which takes an Html.TagHandler
and an Html.ImageGetter
as arguments as well as the text to parse.
In your case you could parse null
as for the Html.TagHandler
but you'd need to implement your own Html.ImageGetter
as there isn't a default implementation.
However, the problem you're going to have is that the Html.ImageGetter
needs to run synchronously and if you're downloading images from the web you'll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter
implementation becomes a lot simpler. You could get away with something like:
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id;
if (source.equals("stack.jpg")) {
id = R.drawable.stack;
}
else if (source.equals("overflow.jpg")) {
id = R.drawable.overflow;
}
else {
return null;
}
Drawable d = getResources().getDrawable(id);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
};
You'd probably want to figure out something smarter for mapping source strings to resource IDs though.
Related Topics
How to Access Files Under Assets Folder of Other APK'S
Ionic2 Background Image Is Resized When Keyboard Is Open
Phonegap & Android - How to Use The New Select List Style
How to Remove Child Nodes in Firebase Android
Intent Filter to Download Attachment from Gmail Apps on Android
Call an Activity Method from a Broadcastreceiver Class
Android, How to Limit Width of Textview (And Add Three Dots at The End of Text)
How to Implement Search in Customlistview Based on Class Item of Pojo Class in Android
Fragment Must Be a Public Static Class to Be Properly Recreated from Instance State
How to Add Padding Between Menu Items in Android
Disable The Swipe Gesture That Opens The Navigation Drawer in Android
Input Field Hidden When Soft Keyboard Appears in Phonegap
How to Apply Custom CSS to Android Webview When Url Is from Internet Server
Android Input Connection Error