Onclick event of the GridView item never gets called…

It is very common to have a click-able UI component (e.g. button) on a GridView item, which in turn sits inside a Android GridView. For example, a GridView may contain a list of thumbnail pictures. Each such picture may have a button or a check mark image (for selecting the image). In such cases, the main event of interest is the OnClick of this button and the Image holder itself. Also depending on the way the code is structured, it may be useful to handle the click event both within this UI component as well as the underlying GridView item.

One common issue is that the over-laying button’s OnClick event swallows the GridView item’s OnClick event – due to this, the GridView item’s OnClick event never gets called. The work-around for this is to replace the Android Button with a TextView styled like a button. This replacement is possible because a Button extends a TextView. The TextView’s OnClick method does not swallow the click event and the OnClick propagates to the GridView item as well, so it can do its own OnClick handling. Some code follows:

public class GridViewAdapter extends ListAdapter {

@Override
public View getView(final int i, View gridviewItem, ViewGroup viewGroup) {
// Inflate the gridview item
gridviewItem = inflater.inflate(R.layout.gridviewItem, viewGroup, false);

// Get the TextView that is contained in the gridview item
final TextView textView = (TextView) gridviewItem.findViewById(R.id.textView1); // instead of R.Id.button1
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// handle onClick of textView here
}
});
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s