Android Gridview未显示assets文件夹中的图像

时间:2014-09-07 10:08:05

标签: java android gridview for-loop assets

我有一个特定的问题,在stackoverflow上还没有回答;我在资产文件夹中的图像编号为0.jpg,1.jpg,2.jpg等。使用for循环我从asssets文件夹中选择三个图像,我试图将这些图像添加到gridview但图像不是展示。活动启动好了没有图像!

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        gridView = (GridView) findViewById(R.id.gridview_result);

        // Sets the Tag
        gridView.setTag(GRIDVIEW_TAG);

        /*
         * Adapt the image for the GridView format
         */
        imageAdapter = new ImageGridViewAdapter(getApplicationContext());
        gridView.setAdapter(imageAdapter);

        // Set the orientation to landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // Retrieve 3 images form the database which appear
        // similar
        for (int i = 0; i < 3; i++) {
            // System.out.println(Retrieval.distances[i][0]);
            image = Retrieval.distances[i][0];
            int num = (int) image;
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(num);
            String imageNum = sBuilder.toString();
            System.out.println(imageNum);

            String file = imageNum + ".jpg";

            try {
                // get input stream
                InputStream ims = getAssets().open(file);
                Log.i("ERROR_IMS", ims + "");
                // load image as Drawable
                Drawable d = Drawable.createFromStream(ims, file);
                // set image to ImageView
                gridView.setBackground(d);
                Log.i("ERROR_d", d + "");
                Log.i("ERROR_gridview", gridView+"");
            } catch (IOException ex) {
                Log.e("I/O ERROR", "Failed when ...");
            }
        }
    }

我认为问题发生在try / catch中。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您应首先获取所有图像并将其设置为适配器。      //将图像设置为ImageView      gridView.setBackground(d); 不会对您的网格项视图产生影响。

一个很好的教程:guide