androidandroid-recyclerviewsnackbaritemtouchhelper

How to add Snackbar where View Class is not directly accessible


I am facing a problem while adding a Snackbar in my code. Actually I want to show a Snackbar in ItemTouchHelper Object. I am using ItemTouchHelper to remove items on swipe and then show a Snackbar that item is removed. How to add a Snakbar where I don't have any access to View object.

final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

        //here I want to add a Snackbar but i don't have access to View object

        int currentPosition = viewHolder.getAdapterPosition();
        Item item = itemList.get(currentPosition);
        int id = item.getId();
        databseHandler.deleteItem(id);
        itemList.remove(viewHolder.getAdapterPosition());
        recyclerViewAdapters.notifyItemRemoved(viewHolder.getAdapterPosition());

    }
});
itemTouchHelper.attachToRecyclerView(recyclerView);

Solution

  • What do you mean with this statement?

    first parameter(View) of Snakbar is not available

    You can call the method that shows your Snackbar from there, and use root view of your Activity layout as an argument for Snackbar.

    private void showSnackbar(String message) {
      View rootView = findViewById(android.R.id.content);
      if(rootView != null) {
        Snackbar.make(rootView, message, Snackbar.LENGTH_SHOW).show(); 
      }
    }
    

    You can call it from your callback:

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    
      //here I want to add a Snackbar but first parameter(View) of Snakbar is not available
       showSnackbar("Your message");
    
       ...
    }