Reputation: 1144
I am trying to add some text and an image in a TextView using Html.fromHtml(), but it's not working.
Getting the string from resources and calling Html.fromHtml():
String insertedText = "<img src=\"small_image\"/>";
String strText = getResources().getString(R.string.big_string, insertedText);
myTextView.setText(Html.fromHtml(strText, context, null));
Where context is an activity that also implements ImageGetter. This is the getDrawable function:
public Drawable getDrawable(String source) {
int id = 0;
Drawable drawable = null;
if(source.equals("small_image")){
id = R.drawable.small_image;
}
if (id > 0) {
drawable = getResources().getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
In the strings.xml file in values, I have:
<string name="big_string">"Big String %1$s"</string>
I have small_image.png in the drawable folder and while debugging, I can see that id gets a correct value and then the bitmap is loaded in the drawable variable, but it still renders the rectangle with 'obj' written in it.
Any idea why it does that?
I also tried using SpannableStringBuilder and add an image span that would have replaced a 'space' from my text, but that didn't work either.
Upvotes: 1
Views: 4722
Reputation: 1060
String name = modelDispatchReportList.get(position).getName(); //get name from model class typed List
String text = "<font color='#000000'>" + name + "</font>"; //change color of name
/* check version of API to call method of Html class because fromHtml method is deprecated
* */
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText("12345" + " "); //set text to textView
holder.textViewName.append(Html.fromHtml(text)); //append text to textView
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("12345" + " "); //set text to textView
holder.textViewName.append(Html.fromHtml(text, 0)); ////append text to textView
}
Upvotes: 1
Reputation: 1144
I have found the problem with my code. Everything I wrote in the question is correct and you can use it as a reference for incorporating images in TextViews.
The problem was that I was using the attribute :
android:textAllCaps="true"
In the xml file and that somehow prevented the image from being shown.
Upvotes: 4
Reputation: 2769
Just change your Textview
into WebView
and set the content to your WebView
Upvotes: 0
Reputation: 3698
well, I tried your code, it' s working...
btw, I used the deafult ic_lancher drawable...
i just simply set the the textview to setContentView
.
i guess is the textview' s layout or drawable' s problem?
could you tell me more?
Upvotes: 0