Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

android get position of clicked item in gridview

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...