内置Listener的适配器getView()

时间:2015-12-02 10:44:41

标签: java android gridview android-arrayadapter adapter

我为此创建了一个GridView和一个适配器。在getView()方法中,我做了这个:

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);
        }
    });

在此方法中编写.setOnClickListener是正确的吗?还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以为每个视图设置一次单击侦听器,而不是每次调用getView()。您还应该考虑是否需要GridView中的按钮,因为通常用户只需单击整个视图即可执行操作。

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

答案 1 :(得分:0)

试试这个教程 http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/ 只需用网格视图替换列表视图,希望这对您有所帮助