Create a clickable image in a GridView in Android

前端 未结 3 811
忘了有多久
忘了有多久 2020-12-09 12:06

I have images displayed in a GridView as in this tutorial. I want to be able to click on a single image and do other events and I need to know what image was clicked.

3条回答
  •  爱一瞬间的悲伤
    2020-12-09 12:21

    I was able to get the position of the clicked image by making the position final and adding an onClick listener to the imageView. This logs the position of the image that was clicked.

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
      ImageView imageView;
      if (convertView == null) {  
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    
    
        imageView.setOnClickListener(new View.OnClickListener() {
    
          @Override
          public void onClick(View view) {
            Log.d("onClick","position ["+position+"]");
          }
    
        });
    
      } 
      else {
        imageView = (ImageView) convertView;
      }
    
      imageView.setImageResource(mThumbIds[position]);
      return imageView;
    }
    

提交回复
热议问题