0

I have a custom adapter which changes the alpha of a view depending on if that particular list item is "valid" or not. I also need to display a toast when the user attempts to click on the invalid item. Unfortunately, due to view recycling, I do not currently see how it is possible to set a different OnClickListener for each view. Eventually the OnClickListener will be applied to every item in the list, valid or not.

The "hacky" way to fix this would be to pass in null as the convertView parameter in super.getView(). I would really prefer to avoid anything like this, if at all possible.

I would appreciate any suggestions, thanks!

public class TestAdapter extends ArrayAdapter<TestModel> {

    class ViewHolder {
        CheckedTextView ctv;

        public ViewHolder(View v) {
            ctv = (CheckedTextView)v.findViewById(android.R.id.text1);
        }
    }

    public TestAdapter(Context context, List<TestModel> testModelList) {
        super(context, R.layout.test_list_item, testModelList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);

        ViewHolder holder = (ViewHolder)v.getTag();
        if (holder == null) {
            holder = new ViewHolder(v);
            v.setTag(holder);
        }

        // Decrease alpha to indicate that the item is invalid.
        holder.ctv.setAlpha(isEnabled(position) ? 1.0f : 0.2f);

        if (!isEnabled(position)) {
            holder.ctv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Show a toast which indicates you tried to select an invalid option.

                    // However, due to view recycling this will eventually apply to
                    // all views in the list.
                }
            });
        }

        return v;
    }

    @Override
     public boolean isEnabled(int position) {
        return getItem(position).isValid();
    }
}

1 Answers1

0

There's a DevBytes video specifically about this problem

DevBytes: ListView Animations

It's about having an ongoing animation continue on a recycled view, but the same concept applies to on click listeners

Or Bar
  • 1,566
  • 11
  • 12