Android get clicked item position in gridview

as we know, using the Android grid view, we can do the following and get a notification when an element is clicked:

gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(PopularCapitActivity.this, "" + position, Toast.LENGTH_SHORT).show(); } }); 

we also know that if a cell in the grid contains a clickable element, say, a button, then the above will not be fired.

so I currently have a grid view, each cell has its own button, so now when the user clicks on the button, it will have its own action based on the cell in which the button is located, to my question, how can I to access cell position in button handler?

thanks

+8
android android-gridview gridview android-widget
source share
2 answers

Assuming you are using a custom adapter for GridVIew, in the getView method, you can simply add a tag to the Button object that contains the position passed to getView:

 button.setTag(new Integer(position)); 

Then, in the onClickListener method with the view that is passed (button), you can:

 Integer position = (Integer)view.getTag(); 

And then from there process the position value.

EDIT: It seems to be best to do:

 button.setTag(Integer.valueOf(position)); 

instead of using the Integer constructor.

+28
source share
 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String a = String.valueOf(position); Toast.makeText(getApplicationContext(), a, Toast.LENGTH_SHORT).show(); } }); 
0
source share

All Articles