是否可以在Android中的图像按钮中将URL中的图像放入?

时间:2009-05-10 08:53:57

标签: android

我想要做的是数据库列表视图 使用右侧的小图像按钮和文本, 我希望小图像用给定的URL改变 一个文本文件,但我被困住,2小时规则已经到了

For(file lenght) 所以URL是www.site.com/images/(i ++)。png

2 个答案:

答案 0 :(得分:10)

您想要做的事情肯定是可能的,但您需要手动获取图像并将其设置在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 pre 1.5中使用带有SDK 1.5的AsyncTaskUserTask),然后只需调用:

myImageButton.setImageBitmap( bitmap );

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

答案 1 :(得分:2)

上面的fetchImage代码失败了 DEBUG / skia(xxxx):--- decoder-> decode返回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;
}