android get position of clicked item in gridview
Asked Answered
V

2

10

as we know using android grid view, we can do the following and get notified when item 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 the cell in the grid contains a clickable item, say a button, the above won't get fired.

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

thanks

Vallombrosa answered 4/10, 2012 at 19:49 Comment(2)
Are you using a custom adapter for the GridView?Hyams
yes i have a custom one just just extending the BaseListAdapterVallombrosa
H
31

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

button.setTag(new Integer(position));

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

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

And then handle the position value from there.

EDIT: It appears the best practice would be to do:

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

rather than using the Integer constructor.

Hyams answered 4/10, 2012 at 19:57 Comment(4)
Oh wow, thank you. My only question is: Why doesn't this answer have 5000 upvotes? Am I the only person putting buttons in GridViews?Parapet
Thanks! I just updated my answer to take into account the best practice. It is recommended to use Integer.valueOf(position) rather than the constructor.Hyams
Great solution! Now, though, Integer.valueOf(position) is not required, just passing position will work, too.Withershins
if you want to get position in gridview you can just use int tag=(int)view.getTag(); int currentRow=tag/9;( my grid is 9*9 hence) int currentCol=tag%9; To set tag i used button.setTag((9*i)+j) during iteration in gridviewSerajevo
P
3
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();
    }
});
Panelboard answered 11/2, 2017 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.