从URL设置选项卡图标图像

时间:2012-08-27 18:28:58

标签: android android-tabhost android-imageview

我有一个应用程序,它有一组标签,图像设置为TabIndecator。我想从URL中获取图像,并将TabIndecator图像设置为为该特定选项卡指定的URL。有办法吗?我可以使用ImageView并将其设置为TabIndecator吗?

2 个答案:

答案 0 :(得分:0)

  

我想从URL中获取图像,并将TabIndecator图像设置为为该特定选项卡指定的URL。有办法吗?

不直接,您必须将图片作为Bitmap下载到设备,并将其打包在BitmapDrawable中,然后将其设置为TabSpect.setIndicator()

  

我可以使用ImageView并将其设置为TabIndecator吗?

当然,如果您愿意,TabSpec.setIndicator()可以将View作为参数。

答案 1 :(得分:0)

此方法允许您从图像的URL获取本地位图。我的评论是西班牙语,但我希望这个例子无论如何都会有用。确保在AsyncTask或类似的(不在UI线程上)运行它:

private static final int IO_BUFFER_SIZE = 8 * 1024;
private static final int MINIMO_TAM = 10;
public static final int MAXIMO_TAM = 640;

public static Bitmap loadRemoteImage(CharSequence urlImagen) {
    if (null == urlImagen) {
        return null;
    }

    Bitmap bm = null;
    InputStream is = null;
    BufferedInputStream bis = null;

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.addRequestInterceptor(new GzipHttpRequestInterceptor());
    httpclient.addResponseInterceptor(new GzipHttpResponseInterceptor());

    try {
        String urlSinEspacios = urlImagen.toString().replace(" ", "+");

        // Hacer la llamada
        HttpGet httpget = new HttpGet(urlSinEspacios);
        HttpEntity entity = httpclient.execute(httpget).getEntity();

        is = entity.getContent();
        bis = new BufferedInputStream(is, IO_BUFFER_SIZE);
        //Obtener solo el tamaño
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(bis, null, o);
        try {
            bis.close();
            is.close();
        } catch (Exception e) {
        }

        //Calcular mejor escala
        int scale = 1;
        if (o.outHeight > MAXIMO_TAM || o.outWidth > MAXIMO_TAM) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(MAXIMO_TAM / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Descargar el real
        entity = httpclient.execute(httpget).getEntity();
        is = entity.getContent();
        bis = new BufferedInputStream(is, IO_BUFFER_SIZE);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inTempStorage = new byte[16 * 1024];
        options.inSampleSize = scale;
        bm = BitmapFactory.decodeStream(bis, null, options);
        // Finalizado
        httpclient.getConnectionManager().shutdown();
    } catch (Exception e) {

        bm = null;
    } finally {
        try {
            bis.close();
            is.close();
            // Finalizado
            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
        }
    }

    return bm;
}

然后,您可以使用BitmapDrawable来包装此Bitmap并使用:

tabHost.newTabSpec("TODO").setIndicator("TODO", TODO).setContent(TODO);