0

I recently witnessed a weird behaviour, when I used ButterKnife to bind an OnClick method of an image button inside an Adapter, as pointed in the title of this question. As suggested in the documentation I declared an inner class ViewHolder, where all the @Bind declarations happen, I also have @OnClick.

My ViewHolder class looks like this:

    class ViewHolder {

    private Product product;

    @Bind(R.id.title)
    TextView text;
    @Bind(R.id.price)
    TextView price;

    public ViewHolder(View view, Product product) {
        ButterKnife.bind(this, view);
        this.product = product;
    }

    @OnClick(R.id.image_button)
    public void launchProductFragment() {
            ProductFragment fragment = new ProductFragment();
            Bundle args = new Bundle();
            args.putInt(Tools.WS_PRODUCT_GROUP_ID, product.getId());                
            FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        }
}

Note: When I set a good old OnClickListener directly in my getView method, the click works properly, and displays the expected result.

Is this a known issue? Or something I did in my implementation causes it?

moud
  • 729
  • 9
  • 19

1 Answers1

1

Do not pass Product in the constructor, pass it in to view holder while in getView() method of Adapter.

class ViewHolder {

    private Product product;

    void bindProduct(Product product) {
        this.product = product;
    }
}

In your Adapter do as follows:

@Override
public void getView(int position, View convertView, ViewGroup parent) {
    // Some code here
    holder.bindProduct(myproductlist.get(position));
    //other code...
}
Abdullah
  • 7,143
  • 6
  • 25
  • 41
  • My bad, I though he/she uses RecyclerView. I will change my answer. – Abdullah Aug 14 '15 at 13:24
  • Thx @Abdullah I'll try your solution and let you know. Any way it seems reasonable since the holder gets taken from view tag when the view is not null, I did miss that :/ – moud Aug 14 '15 at 14:51
  • @Mood Please accept if it solved your issue. Thanks. – Abdullah Aug 15 '15 at 10:17