Adapter getView() with Listener inside

I created a GridView and an Adapter for that. In the getView() method, I made this:

public View getView(int position, View convertView, ViewGroup parent) {
    viewHolder = new RecordHolder();
    final Sticker sticker = data.get(position);
    if (convertView == null) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId, parent, false);

        viewHolder.count = sticker.getAmount();
        viewHolder.textViewNumber = (TextView) convertView.findViewById(;
        viewHolder.textViewQuantity = (TextView) convertView.findViewById(;
        viewHolder.iv_logo_card = (ImageView) convertView.findViewById(;
        viewHolder.buttonAdd = (ImageButton) convertView.findViewById(;
        viewHolder.buttonRemove = (ImageButton) convertView.findViewById(;
        paintQuantity(viewHolder.count, viewHolder, context);

    } else {
        viewHolder = (RecordHolder) convertView.getTag();

    viewHolder.buttonAdd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (viewHolder.count != 99) {
            paintQuantity(viewHolder.count, viewHolder, context);

It's correct to write the .setOnClickListener inside this method? Exists a better way to do this?


You can set the click listener once for each view, rather than every time getView() is called. You should also probably consider whether you want a button in a GridView, as generally users would just click the whole View to perform an action.

if (convertView == null) {
    // add listener here

try this tutorial just replace the list view with the grid view hope this will help you

Need Your Help

Hiding ActionBar from ActionBarActivity after a Splash Fragment

java android

Basically the launcher is the ActionBarActivity that calls the Fragment(splash) and then back to ActionBarActivity. THe problem is before the splash became visible the actionbar shows up and then the

CakePHP 2.4 - DB Update Doesn't Save All Passed Data One Field is Never Persisted

php mysql cakephp cakephp-2.4

I'm trying to update the DB using some data pulled from an external API. The appstatus and amount both come from the same API, and I can see the values are correct, and they make it all the way down