Android GridView Custom BaseAdapter ImageView ImageButton OnItemClick doesn´t work

Posted by Marek on Stack Overflow See other posts from Stack Overflow or by Marek
Published on 2011-05-24T15:34:08Z Indexed on 2012/09/20 3:38 UTC
Read the original article Hit count: 445

Filed under:
  • i have a problem using a GridView with a CustomAdapter (extends BaseAdapter).
  • any Activity implements the OnItemClickListener.
  • if i use ImageView as item everything works fine, OnItemClick-Events will be fired/catched

I have not found a useful example for a GridView with a custom BaseAdapter using ImageButton. Has anyone an idea? Many thanks in advantage!

Snippets:

class MyActivity extends Activity implements OnItemClickListener {
  ...
  @Override
  public void onCreate() {
    ...
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setOnItemClickListener(this);
    gridview.setAdapter(new ImageButtonAdapter(this));
  }
  ...    
  @Override
  public void onItemClick(AdapterView<?> adapter, View view, int arg2, long arg3)
  {
    Log.e("onItemClick()", "arg2=" + arg2 + ", arg3=" + arg3);
  }
}


public class ImageButtonAdapter extends BaseAdapter
{
  private Context    mContext;

  public LayoutMenuAdapter(Context c)
  {
    mContext = c;
  }

  public int getCount()
  {
    return mThumbIds.length;
  }

  public Object getItem(int position)
  {
    return null;
  }

  public long getItemId(int position)
  {
    return 0;
  }

  public View getView(int position, View convertView, ViewGroup parent)
  {

    /* IF I USE THIS PART EVERYTHING WORKS FINE */

    // ImageView imageView;
    // if (convertView == null) {
    //    imageView = new ImageView(mContext);
    //    imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
    //    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    //    imageView.setPadding(0, 0, 0, 0);
    //    imageView.setFocusable(false);
    //  } else {
    //    imageView = (ImageView) convertView;
    //  }
    //  imageView.setImageResource(mThumbIds[position]);
    //  return imageView;

    /* IF I USE THIS PART NO THE ACTIVITY/LISTENER RECEIVES NO EVENT */

    ImageButton imageButton;
    if (convertView == null) {
      imageButton = new ImageButton(mContext);
      imageButton.setLayoutParams(new GridView.LayoutParams(100, 100));
      imageButton.setScaleType(ImageView.ScaleType.CENTER_CROP);
      imageButton.setPadding(0, 0, 0, 0);
      imageButton.setFocusable(false);
    } else {
      imageButton = (ImageButton) convertView;
    }
    imageButton.setImageResource(mThumbIds[position]);
    return imageButton;
  }

  // references to images
  private Integer[] mThumbIds = { R.drawable.media};
}

© Stack Overflow or respective owner

Related posts about android