使用Picasso从网格中加载SD卡中的图像

时间:2015-02-21 13:12:30

标签: android image android-sdcard picasso

我的网格包含字符串arraylist:

    final GridView grid = (GridView) view.findViewById(R.id.gridview);
    final ArrayList<String> items = new ArrayList<String>();

    items.add("1a");
    items.add("1b");
    items.add("1c");
    items.add("1d");
    items.add("1e");
    items.add("2a");
    items.add("2b");
    items.add("2c");
    items.add("2d");
    items.add("2e");
    items.add("3a");
    items.add("3b");
    items.add("3c");
    items.add("3d");
    items.add("3e");
    items.add("3f");
    items.add("4a");
    items.add("4b");
    items.add("4c");
    items.add("4d");
    items.add("4e");
    items.add("4f");
    items.add("4g");

后来,我尝试用onClick做一些事情,选择某个位置:

 grid.setAdapter(new GridAdapter(items));

        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                  if(position == 3)
                      ...
            }
        });

我想要的是:

我在res/drawable文件夹中有20张图片。我想要一个包含imageView的片段,它在onClick上运行,并将名为1a.png的图片加载到项目1a,1b.png到项目1b等等,而不选择某些位置。

所以当我在gridview中点击1a时,它会显示1a.png,1b显示1b.png,等等......

感谢。

1 个答案:

答案 0 :(得分:0)

因为ArrayList列表包含位于res/drawable文件夹中的所有图像名称。所以不需要使用if-elsewitch-case根据GridView中的点击项获取图像:

1. onItemClick上的点击项目名称发送到下一个要使用Intent显示所选图像的活动。像:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
     String selectedImage = grid.getItemAtPosition(position);
     // prepare Intent for starting next Activity:

     Intent intent=new Intent(....);
     intent.putExtra("selectedImage", selectedImage);
     // start next Activity or Fragment....
  }

2. 在下一个Activity中从Intent获取图片名称,并使用getIdentifier在onCreate方法中使用name获取可绘制ID:

Intent intent = getIntent();
String selectedImage = intent.getStringExtra("selectedImage");
int identifier = getResources().getIdentifier(selectedImage, 
                                    "drawable",getPackageName());

在ImageView的identifier方法中传递setImageResource以显示所选图像。