【问题标题】:Is it possible to put an image from a URL in a imagebutton in android?是否可以将来自 URL 的图像放入 android 的 imagebutton 中?
【发布时间】:2010-10-25 02:29:25
【问题描述】:

我想做的是一个数据库列表视图 右侧有一个小图像按钮和文本, 我希望小图像使用由给出的 URL 进行更改 一个文本文件,但我被卡住了,2 小时规则结束了

对于(文件长度) 所以 URL 是 www.site.com/images/(i++).png

【问题讨论】:

  • 我想我想做的是。由于各种原因,不可能。
  • 可能并非不可能。你能试着更彻底地解释一下这个问题吗?

标签: android


【解决方案1】:

您想要做的事情肯定是可能的,但是您需要手动获取图像并将其设置在 ImageButton 上。

这里有一个小方法可以用来获取图片:

private Bitmap fetchImage( String urlstr )
{
    try
    {
        URL url;
        url = new URL( urlstr );

        HttpURLConnection c = ( HttpURLConnection ) url.openConnection();
        c.setDoInput( true );
        c.connect();
        InputStream is = c.getInputStream();
        Bitmap img;
        img = BitmapFactory.decodeStream( is );
        return img;
    }
    catch ( MalformedURLException e )
    {
        Log.d( "RemoteImageHandler", "fetchImage passed invalid URL: " + urlstr );
    }
    catch ( IOException e )
    {
        Log.d( "RemoteImageHandler", "fetchImage IO exception: " + e );
    }
    return null;
}

当然,您会希望将此方法包装在一个线程中(在 SDK 1.5 中使用 AsyncTask 或在 SDK pre 1.5 中使用 UserTask),然后只需调用:

myImageButton.setImageBitmap( bitmap );

我认为这已经回答了您的问题,如果没有,请进一步详细说明。

【讨论】:

  • 如果你喜欢我并且你的列表相当长并且图像可能很大,那么行“img = BitmapFactory.decodeStream(is );”会让你很快进入 OOM(内存不足)领域。幸运的是,SO 对此也有很多答案。只是需要注意的事情。 gl!
【解决方案2】:

上面的 fetchImage 代码失败
DEBUG/skia(xxxx): --- decoder->decode returned false
如果它被重复调用。
(StackOverflow.com 上已经对此进行了多次讨论)

这不是崩溃或可捕获的错误,而是返回一个空位图。

这个替代的 fetchImage 有效(谁能说出为什么?):

    private Bitmap fetchImage(String urlstr){
    InputStream is= null;
    Bitmap bm= null;
    try{
        HttpGet httpRequest = new HttpGet(urlstr);//bitmapUrl.toURI());
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
        is = bufHttpEntity.getContent();
        bm = BitmapFactory.decodeStream(is); 
    }catch ( MalformedURLException e ){
        Log.d( "RemoteImageHandler", "fetchImage passed invalid URL: " + urlstr );
    }catch ( IOException e ){
        Log.d( "RemoteImageHandler", "fetchImage IO exception: " + e );
    }finally{
        if(is!=null)try{
            is.close();
        }catch(IOException e){}
    }
    return bm;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2011-06-14
    相关资源
    最近更新 更多