android get position of clicked item in gridview

后端 未结 2 972
情书的邮戳
情书的邮戳 2020-12-13 16:39

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

gridview.setOnItemClickListener(new AdapterView.OnItemClic         


        
相关标签:
2条回答
  • 2020-12-13 17:04
    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 讨论(0)
  • 2020-12-13 17:07

    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.

    0 讨论(0)
提交回复
热议问题