单击gridview图像的事件

时间:2014-02-01 06:51:24

标签: android gridview

我有一个gridview代码,可以在任何设备上自动设置图像。但问题是我想在新活动中打开特定图像,但我的图像存储在LayoutInflator中。所以请为我提供一些代码。

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}

private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;

public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);

items.add(new Item("Image 1", R.drawable.nature1));
items.add(new Item("Image 2", R.drawable.nature2));
items.add(new Item("Image 3", R.drawable.tree1));
items.add(new Item("Image 4", R.drawable.nature3));
items.add(new Item("Image 5", R.drawable.tree2));
}

@Override
public int getCount() {
return items.size();
}

@Override
public Object getItem(int i)
{
return items.get(i);
}

@Override
public long getItemId(int i)
{
return items.get(i).drawableId;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;

if(v == null)
{
v = inflater.inflate(R.layout.gridview_item, viewGroup, 
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}

picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);

Item item = (Item)getItem(i);

picture.setImageResource(item.name.setText(item.name);

return v;
}

private class Item
{
final String name;
final int drawableId;
Item(String name, int drawableId)
{ 
this.name = name;
this.drawableId = drawableId;
}
}
}
}

这是我在imageadapter活动中的点击事件代码。

public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent i = new Intent(this, FullImageActivity.class);
i.putExtra("src", position);
mactivity.startActivity(i);
}

这是我在新活动中获取图像的代码,即FullImageActivity。

imageView = (ImageView) findViewById(R.id.full_image_view);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
int res = extras.getInt("src");
imageView.setImageResource(res);

}

1 个答案:

答案 0 :(得分:1)

 1. Create the instance for activity in your adapter class

    `Activity mactivity;`

 2. Pass the **activity instance** to you adapter constructor class *[public
    MyAdapter(Context context,Activity activty)]*. And store it in your adapter class.

    `public MyAdapter(Context context,Activity activity){
     inflater  = LayoutInflater.from(context);
     mactivity = activity;
    }`

 3. Set *onClickListner* for your image in *getView()*. And use the following code for click action

    `Intent mIntent = new Intent(this,newActivity.class);
     mIntent.putExtras(bundle);
     mactivty.startActivity(mIntent);`