【问题标题】:Load images from sdcard in grid with Picasso使用毕加索在网格中从 sdcard 加载图像
【发布时间】:2015-02-21 13:12:29
【问题描述】:

我有一个包含项目字符串数组列表的网格:

    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等等...

谢谢。

【问题讨论】:

  • 那你遇到了什么问题?
  • @ρяσѕρєяK 我找不到办法。我无法让 1a 加载 1a.png,让 1b 加载 1b.png 而无需使用带有位置的 if 语句。

标签: android image android-sdcard picasso


【解决方案1】:

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

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

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 方法中使用名称获取可绘制 id:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多