android获取gridview中点击项目的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12734793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:37:52  来源:igfitidea点击:

android get position of clicked item in gridview

androidgridviewandroid-widgetandroid-gridview

提问by user1697965

as we know using android grid view, we can do the following and get notified when item is clicked:

正如我们知道使用 android 网格视图,我们可以执行以下操作并在单击项目时收到通知:

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

谢谢

回答by dennisdrew

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:

假设您正在为 GridVIew 使用自定义适配器,在 getView 方法中,您可以简单地向包含传递给 getView 的位置的 Button 对象添加一个标签:

button.setTag(new Integer(position));

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

然后,在 onClickListener 方法中,使用传入的视图(按钮),您可以执行以下操作:

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.

而不是使用 Integer 构造函数。

回答by Mirza Adil

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();
    }
});