【问题标题】:setImageResource with JSON data带有 JSON 数据的 setImageResource
【发布时间】:2013-10-29 01:50:55
【问题描述】:

如何将我以 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;
        }

这里我默认设置了drawable文件夹中的图像,但是我必须将我得到的图像设置为json,我该怎么做?

【问题讨论】:

    标签: android json


    【解决方案1】:

    这里我默认设置了可绘制文件夹中的图像,但我必须设置 我以 json 格式获取的图像,我该怎么做?

    为了显示您从服务器返回的 JSON 中获取的 web url 中的图像,您需要首先下载可用缓存或存储中的图像。下载图片后获取位图并传递给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;
        }
    

    使用AsyncTaskHandler 调用download_Image 方法以避免NetworkOnMainThreadException

    如果您使用 ListView 或 GridView 视图,请使用 Universal Image Loader

    【讨论】:

    • 不下载就不能这样做吗?
    • @thumbernirmal:是的,无法从 url 将 src 设置为 ImageView
    猜你喜欢
    • 2018-12-04
    • 2014-11-02
    • 2016-09-03
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2016-09-24
    • 2018-07-16
    相关资源
    最近更新 更多