0

I have two RecyclerViews in my app, who both contain their own adapters. Both of the adapters have their own static viewHolder. The ViewHolder is static in order to prevent memory leaks coming from created and remaining instances.

These static ViewHolder classes look exactly alike, with one or two parameters difference. I would like to short the adapter classes' code by having a ViewHolder factory, but since the ViewHolder classes need to be static, I am not sure if what I want is possible.

Is there a way to short the duplicate code in this matter? Or should I just keep peace with 'large' adapter classes.

StorageViewHolder

static class StorageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
    // the repeating item in the adapter
    final Button storageItemView;
    Context _context;

    // constructor setting the clicklisteners and buttons
    StorageViewHolder(View itemView, Context context, RecyclerviewClickListener listener)
    {
        super(itemView);
        _listener = listener;
        _context = context;
        storageItemView = itemView.findViewById(R.id.storageButton);
        itemView.setOnClickListener(this);
    }

    public void setOnItemClickListener(RecyclerviewClickListener clickListener)
    {
        StorageListAdapter._listener = clickListener;
    }

    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent(_context, StorageActivity.class);
        intent.putExtra("storageID", ((Button) v).getId());
        _context.startActivity(intent);
    }
}

ShelfViewHolder

static class ShelfViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
    // the repeating item in the adapter
    final Button shelfItemView;
    Context _context;

    // constructor setting the clicklisteners and buttons
    ShelfViewHolder(View itemView, Context context, RecyclerviewClickListener listener)
    {
        super(itemView);
        _listener = listener;
        _context = context;
        shelfItemView = itemView.findViewById(R.id.storageButton);
        itemView.setOnClickListener(this);
    }

    public void setOnItemClickListener(RecyclerviewClickListener clickListener)
    {
        ShelfListAdapter._listener = clickListener;
    }

    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent(_context, ShelfActivity.class);
        intent.putExtra("shelfID", ((Button) v).getText().toString());
        _context.startActivity(intent);
    }
}
MwBakker
  • 498
  • 5
  • 18

0 Answers0