Apurva Apurva - 1 year ago 89
Android Question

Change DataSet on RecyclerView item click

I am working on a project in which I need to change data of recyclerView after recyclerView item is clicked. I have tried setOnClickListener in onBindViewHolder method:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Dataset> mDataset = Collections.emptyList();
private static Context sContext;
private SharedPreferences sharedPrefs;

// Create new views (invoked by layout manager)
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View v = null;

sharedPrefs = Functions.getShPreferences(parent.getContext(), "selected_view");
viewType = sharedPrefs.getInt("selected_view", 0);
switch (viewType) {
case 0:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
case 1:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_view, parent, false);

// set the view's size, margins, paddings and layout parameters

return new ViewHolder(v);

// Replace the contents of a view (invoked by layout manager)
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final Dataset current = mDataset.get(position);

holder.mLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

// make your click listener here
String f = Functions.getRoot(current.getFile());

mDataset = Functions.getData(f);
new FileAdapter(sContext, f);
Toast.makeText(v.getContext(), f, Toast.LENGTH_SHORT).show();


// Return the size of your dataset (invoked by layout manager)
public int getItemCount() {
return mDataset.size();

public int getItemViewType(int position) {

return super.getItemViewType(position);

public static class ViewHolder extends RecyclerView.ViewHolder {
TextView mName;
ImageView mIcon;
RelativeLayout mLayout;
//TextView mFileDateModified;

public ViewHolder(View v) {
mLayout = (RelativeLayout) v.findViewById(R.id.recycler_view_layout);
mName = (TextView) v.findViewById(R.id.file_name);
mIcon = (ImageView) v.findViewById(R.id.file_icon);


public MyAdapter(Context context, String ph) {
context = sContext;
mDataset = Functions.getData(ph);

I have put this code in onBindViewHolder. But its not working. Any help will be appreciated. Thank you.

Answer Source

You can set your listener in your ViewHolder inner class. Code would be like;

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public ViewHolder(View itemView) {

    public void onClick(View v) {
        mDataset = Functions.getData();
        new FileAdapter();

        int position = getAdapterPosition();
        // or
        position = getLayoutPosition();
        // both worked for me