使用TextView.setText将具有html图像标记的字符串转换为图像(Html.fromHtml(string))

时间:2013-02-25 04:02:30

标签: android android-layout

我有一个字符串,如下所示:

String text = "<img src="https://www.google.com/images/srpr/logo3w.png">"

当我这样做时

TextView.setText(Html.fromHtml(text));

我需要将图像显示在活动中。

我不想使用WebView。

请告知我们实现这一目标的其他方法。

3 个答案:

答案 0 :(得分:1)

你必须使用asynctask,在doInbackground()设置图片中打开连接到onPostExecute()

中的textview
try {
        /* Open a new URL and get the InputStream to load data from it. */
        URL aURL = new URL("ur Image URL");
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        /* Buffered is always good for a performance plus. */
        BufferedInputStream bis = new BufferedInputStream(is);
        /* Decode url-data to a bitmap. */
        Bitmap bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();

        Drawable d =new BitmapDrawable(bm);
       d.setId("1");
 textview.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
        } catch (IOException e) {
        Log.e("error", "Remote Image Exception", e);
        } 

希望它会有所帮助。

答案 1 :(得分:1)

答案 2 :(得分:0)

您需要在strings.xml

中定义文字
<string name="nice_html">
<![CDATA[<img src='https://www.google.com/images/srpr/logo3w.png'>
]]></string>

然后,在您的代码中:

TextView foo = (TextView)findViewById(R.id.foo); 
foo.setText(Html.fromHtml(getString(R.string.nice_html)));