带有JSON数据的setImageResource

时间:2013-10-28 17:43:12

标签: android json

如何将我作为JSON获取的图像设置为imageview?以下是我的代码..

 try {
               JSONObject responseObject = json.getJSONObject("responseData");
               JSONArray resultArray = responseObject.getJSONArray("results");
               private ArrayList<Object> listImages;
               listImages = getImageList(resultArray);
               } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

现在,我想将图像设置为imageview,如下所示......

 private int[] GalImages = new int[] { R.drawable.h, R.drawable.i};
    public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setImageResource(GalImages[position]);

            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

这里我设置了可绘制文件夹的默认图像,但是我要设置我作为json获取的图像,我该怎么做?

1 个答案:

答案 0 :(得分:0)

  

这里我默认设置了drawable文件夹中的图片,但我要设置   我作为json得到的图像,我该怎么做?

用于显示从服务器返回的JSON中获取的网址的图像,您需要先在可用的缓存或存储中下载图像。下载图像后获取位图并将其传递给ImageView.setImageBitmap

   private Bitmap download_Image(String url) {

        Bitmap bmp =null;
        try{
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = con.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }

使用download_ImageAsyncTask调用Handler方法以避免NetworkOnMainThreadException

如果您使用的是ListView或GridView Views,请使用Universal Image Loader