Android从java代码添加drawable图像?

时间:2015-11-20 08:06:17

标签: android drawable

我需要在TextView中插入一个drawable,我在代码中从web下载。因此,我无法手动将图像放入res和R.drawable中。

我该如何使用它?

2 个答案:

答案 0 :(得分:2)

步骤:

1)下载图片

2)转换为drawable

3)通过调用smth将drawable设置为textView:

textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

答案 1 :(得分:0)

试试这个

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("DEBUGTAG", "Remote Image Exception", e);
    } 

参考网址How to display an image from an URL within textView