Search code examples
javaandroidadapterandroid-context

Switching to a fragment on click from the adapter


I have a BackStack in the project, to make the transition from fragment to fragment I use the following

 public void showFragment(@NonNull Fragment fragment) {
        showFragment(fragment, true);
    }

    public void showFragment(@NonNull Fragment fragment, boolean addToBackStack) {
        if (curFragment != null && addToBackStack) {
            pushFragmentToBackStack(curTabId, curFragment);
        }
        replaceFragment(fragment);
    }
 private void replaceFragment(@NonNull Fragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tr = fm.beginTransaction();
        tr.replace(R.id.content, fragment);
        tr.commitAllowingStateLoss();
        curFragment = fragment;
    }

But I need to step into fragment by clicking item from recyclerView, to do this, I added a position for each item. And onBindViewHolder in Adapter added this

 @Override
    public void onBindViewHolder(MenuViewHolder holder, int position) {
        ItemMenu Item = ItemMenuList.get(position);

        holder.tv_menu.setText(Item.getMenuText());

        holder.getAdapterPosition();

        holder.cv_menu.setOnClickListener(v ->
        {
            switch (Item.getInitialPositon()) {
                case 0: {
                    ((MainActivity) requireActivity()).showFragment(Fragment_Tasks.newInstance());
                    break;
                }
                case 1: {

                    break;
                }
            }
        });
    }

The problem is that the transition requires context(). How to fix it?


Solution

  • You can either pass a Context reference into your adapter or a callback which you can use to pass the job of click handling to the activity/fragment.

    For an example with a callback, we can define an interface:

    interface OnItemClickListener {
         void onItemClick(...);
    }
    

    Pass this into the adapter via the constructor, then trigger it when your item is clicked. So in onBindViewHolder:

    holder.cvMenu.setOnClickListener(v -> {
        itemClickListener.onItemClick(...);
    });