0
class Fragment extends Fragment() implements Callback {
    @Ovverride
    onCreate(SavedInstanceState savedInstanceState) {
        Adapter adapter = new Adapter(getContext())
    }
   
    @Ovverride
    someCallbackMethod() { // Code when callback is called }
}

class Adapter extends RecyclerView.Adapter<VH>() {
    Context context;
    public Adapter(Context context) {this.context = context}
    class VH extends RecyclerView.ViewHolder {
        private void bind() {
            button.setOnClickListener (v-> { 
                BottomSheet sheet = BottomSheet.newInstance(variable);
                sheet.show(((FragmentActivity) context).getSupportFragmentManager(), 
           sheet.getClass().getName());
        })
    }
}

class BottomSheet extends BottomSheetDialogFragment {
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Callback) listener = 
            (Callback) context;
        else Log.v("BottomSheet", "Not instance");
    }
}

Even though the main fragment implements the callback the context of that fragment is never the instance of the callback what might be the reason for this and how can it be fixed. Note: There might be some errors here and there because I made a generic view of the classes.

Aziz Agasi
  • 53
  • 7
  • 1
    `new Adapter(getContext())` - instead of `getContext()` pass `this`. Your fragment contains the callback listener , so you need to pass reference of fragment. Also you code shouldn't be in `onCreate()` for fragment – Nitish Dec 20 '21 at 06:56
  • @Nitish passing this as an argument causes an error saying that type expected was Context but got type as Fragment – Aziz Agasi Dec 20 '21 at 07:05
  • You need to change here also `Adapter(Context context)` , Add one more parameter of type `Callback` , . if you want to listen to callback, – Nitish Dec 20 '21 at 07:06
  • That won't work since I have to assign the callback variable to bottom sheet in onAttach only to avoid crashes – Aziz Agasi Dec 20 '21 at 07:07
  • Don't change the bottomsheet code, but since your bottom sheet opens from adapter, you need callback instance in a adapter. Or from adpater give a callback to your fragment on `button.setOnClickListener`, and from fragment open the bottom sheet. – Nitish Dec 20 '21 at 07:10
  • 1
    I answered a similar question yesterday . [have a look](https://stackoverflow.com/a/70404385/4168607). – ADM Dec 20 '21 at 08:34

1 Answers1

0

A Fragment does not inherit from Context. Your easiest solution would be to implement your Callback in the Activity (which is a Context) that contains the Fragment.

npace
  • 4,218
  • 1
  • 25
  • 35