2021年3月25日星期四

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?

https://stackoverflow.com/questions/66810795/switching-to-a-fragment-on-click-from-the-adapter March 26, 2021 at 11:50AM

没有评论:

发表评论