【问题标题】:Trying to set an image in textView from in Strings.xml in android试图在 android 的 Strings.xml 中设置 textView 中的图像
【发布时间】:2014-09-03 04:35:27
【问题描述】:

我正在尝试在 strings.xml 中设置存储在 assets 文件夹中的图像并将该字符串设置为 TextView。这可能吗?

Strings.xml 有以下字符串:

<string name="nofriends">No Friends.. <![CDATA[<br><br><br><br> <img src=\"file:///android_asset/sad.png\"/>]]></string>

在我的 java 文件中,我正在设置类似这样的内容“

Spanned text = Html.fromHtml(res.getString(R.string.nofriends));
noFriends.setText(text);

我得到带有绿色小框的文本,但不是实际图像?

谁能帮我解决这个问题?

【问题讨论】:

  • textview 是用来显示文本的,你可以使用 imageviews 来代替。
  • 设置 android:drawable left,right,bottom,top 以显示带有 textview 文本的图像

标签: java android xml


【解决方案1】:

您可以使用 ImageGetter 从可绘制资源中获取图像。

ImageGetter imageGetter = new ImageGetter() {

    @Override
    public Drawable getDrawable(String source) {
        Drawable d = getResources().getDrawable(R.drawable.yourimage);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        return d;
    }
};

Spanned spanned = Html.fromHtml(
    "<img src='" + getResources().getDrawable(R.drawable.yourimage) + "'/>", imageGetter, null);

现在将其设置为 TextView

textView.setText(spanned);

编辑

<string name="nofriends">No Friends.. ####</string> //#### to replace with image

String s=res.getString(R.string.nofriends);
s=s.replace("####",spanned);
textView.setText(s);

【讨论】:

  • 太棒了。谢谢@Ketab Ahir。有了这个和一些适合我的项目的更改..解决了这个问题。
【解决方案2】:

TextView 不是为这样使用而设计的。您应该做的是在 TextView 上设置 drawable 属性。

查看类似问题的精彩答案here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多