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(R.id.textViewNumber);
        viewHolder.textViewQuantity = (TextView) convertView.findViewById(R.id.textViewQuantity);
        viewHolder.iv_logo_card = (ImageView) convertView.findViewById(R.id.iv_logo_card);
        viewHolder.buttonAdd = (ImageButton) convertView.findViewById(R.id.buttonAdd);
        viewHolder.buttonRemove = (ImageButton) convertView.findViewById(R.id.buttonRemove);
        viewHolder.textViewQuantity.setText(sticker.getAmount().toString());
        paintQuantity(viewHolder.count, viewHolder, context);
        convertView.setTag(viewHolder);

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

    viewHolder.buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (viewHolder.count != 99) {
                viewHolder.count++;
            }
            sticker.setAmount(viewHolder.count);
            StickerBusinessService.saveSticker(sticker);
            viewHolder.textViewQuantity.setText(sticker.getAmount().toString());
            paintQuantity(viewHolder.count, viewHolder, context);
        }
    });

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

Answers


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 http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/ 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