Android的html.fromHtml不工作



我正在尝试使用Html.fromHtml()在TextView中添加一些文本和图像,但它不起作用。

从资源中获取字符串并调用Html.fromHtml():

String insertedText = "<img src="small_image"/>";
String strText = getResources().getString(R.string.big_string, insertedText);
myTextView.setText(Html.fromHtml(strText, context, null));

context是一个也实现了ImageGetter的activity。这是getDrawable函数:

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

在values中的strings.xml文件中,我有:

<string name="big_string">"Big String %1$s"</string>

我在drawable文件夹中有small_image.png,在调试时,我可以看到id得到一个正确的值,然后位图被加载到drawable变量中,但它仍然渲染矩形,其中写有'obj'。

知道为什么会这样吗?

我还尝试使用SpannableStringBuilder并添加一个图像跨度,从我的文本中替换'空间',但这也不起作用。

我发现我的代码有问题。我在问题中所写的一切都是正确的,您可以将其用作在TextViews中合并图像的参考。

问题是我使用了属性:
android:textAllCaps="true"

在xml文件中,以某种方式阻止图像显示

  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
    }

好吧,我试了你的代码,它的工作…

顺便说一句,我使用了聋的ic_lancher drawable…

我只是简单地设置textview为setContentView

我猜是textview的布局或drawable的问题?

你能告诉我更多吗?

只需将Textview更改为WebView并将内容设置为WebView

不能通过html设置textview上的图像

最新更新