Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static ViewHolder and getting context when using with RecyclerView

I'm trying to use a recycler view and handle on click event. I've read various methods of handling onClick event on a recycler view item like :

  1. Define the click listener inside the view holder class itself.
  2. Define the click listener in onCreateViewHolder().
  3. Define an interface and then go from there (seems like too much work).

So my first question is which option is better? I'm currently using the first method and if defining the click listener in the view holder class itself is the way to go, then how do I use the context from the adapter as the view holder class is static.

Basically, I want to have a static view holder and on click event, open a new Activity for which I need the context.

UPDATE : Adding adapter and ViewHolder code.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context mContext;
    private List<Job> jobs;

    public MyAdapter(Context context, List<Job> jobs) {
        mContext = context;
        this.jobs = jobs;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemLayoutView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.list_item, viewGroup, false);

        itemLayoutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, MyActivity.class);
                mContext.startActivity(intent);
            }
        });

        return new ViewHolder(itemLayoutView);
    }

    @Override
    public void onBindViewHolder(WorkExperienceAdapter.ViewHolder viewHolder, int i) {
            //bindViewHolder code
        }
    }

    @Override
    public int getItemCount() {
        return jobs.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        @InjectView(R.id.current)
        TextView mCurrent;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.inject(this, itemView);
        }
    }
}
like image 530
akshayt23 Avatar asked Jan 06 '23 19:01

akshayt23


1 Answers

In the view holder constructor we get the object of View class. You can use that object to get the context like:

class Holder extends RecyclerView.ViewHolder {

    public Holder(View itemView) {
    super(itemView);
    Context context = itemView.getContext();
   }

}
like image 175
Bhawna Raheja Avatar answered Jan 31 '23 09:01

Bhawna Raheja