Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

butterknife @OnClick inside ViewHolder in CustomAdapter

I'm currently learning butterknife, and I need to bind specific @OnClicks on different views generated by my customer adapter. How do I go about with this?

I've seen an answer in one of the questions here saying that he uses '@onclick' inside the 'ViewHolder'. I'm not sure how to implement this exactly. Any ideas?

Thanks!

like image 260
GonnaGetGet Avatar asked Dec 24 '22 21:12

GonnaGetGet


1 Answers

Imagine you have a ViewHolder like this.

static class ViewHolder {

    @InjectView(R.id.user_name)
    TextView userName;

    @InjectView(R.id.user_title)
    TextView userTitle;


    public ViewHolder(View view) {
        ButterKnife.inject(this, view);
    }

}

You can bind events in your adapters getView method for each view in your holder.

 @Override
public View getView(int position, View convertView, ViewGroup parent) {

    final ViewHolder holder;
    if (convertView != null) {
        holder = (ViewHolder) convertView.getTag();
    } else {
        convertView = LayoutInflater.from(mContext).inflate(
                R.layout.your_row_layout, parent, false);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
    }

   holder.userName.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Your stuff here
        }
    });


    holder.userTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           //Your stuff here  
        }
    });

    return convertView;

}
like image 53
Ugur Avatar answered Jan 20 '23 16:01

Ugur