在新活动中获取gridview图像

时间:2013-08-21 12:14:20

标签: android android-intent android-gridview

我试图将点击/选中的图片发送到新活动这里是我的代码

public int getCount() {
    return mThumbIds.length;
}
public View getView(final int position, View convertView, ViewGroup parent) {
        ImageView imageView; 
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(mContext,HeroData.class);
                    intent.putExtra("imageID", position);
                    mContext.startActivity(intent);
                }
            });
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;

    }

private Integer[] mThumbIds = {
        R.drawable.pic1, R.drawable.pic12,
        R.drawable.pic2, R.drawable.pic13,
        R.drawable.pic3, R.drawable.pic14,

};

}

并尝试在新活动中接收

Bundle bdl = getIntent().getExtras();
    int index = bdl.getInt("imageID");
    ImageView image = (ImageView) findViewById(R.id.imageview);
    image.setImageResource();//the problem ! how to receive the selected image

我想知道即时发送(“imageID”,位置);如何获取所选图像

3 个答案:

答案 0 :(得分:2)

由于您要发送资源,因此可以发送资源ID,而不是它在数组中的索引。像这样:

intent.putExtra("imageID", mThumbIds[position]);
mContext.startActivity(intent);

在你的活动中:

Bundle bdl = getIntent().getExtras();
int imageRes = bdl.getInt("imageID");
ImageView image = (ImageView) findViewById(R.id.imageview);
image.setImageResource(imageRes);

希望有所帮助。

答案 1 :(得分:1)

像这样使用......

gridView.setOnItemClickListener(new OnItemClickListener()   
    {

        public void onItemClick(AdapterView<?> parent, View v,int position, long id) 

        {

            Intent i = new Intent(getApplicationContext(), HeroData.class);



            i.putExtra("imageID", position);

             startActivity(i);


        }
    });

需要对网格视图进行单击...

答案 2 :(得分:0)

您可以将可绘制资源保存在其他位置,例如,您可以在资源中执行此操作,如字符串数组

<resources>

<string-array name="thumbs_imgs">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
</string-array>

</resources>

然后通过索引绘制你需要的东西

TypedArray imgs = getResources().obtainTypedArray(R.array.thumbs_imgs);
//get resourceid by index
mImgView1.setImageResource(imgs.getResourceId(i, -1));