I cannot see any downside of passing the Context
in the constructor and store it in a field. Anyway you could access it in this way:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
//Do your things
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Context context = holder.itemView.getContext();
//Do your things
}
}
Just for completeness, I post the solution I usually adopt which keeps also a reference to the LayoutInflater
:
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
public Context mContext;
public LayoutInflater mInflater;
public MyAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = mInflater.inflate(R.layout.row, parent, false);
//Do your things
}
}