How to call getFragmentManager on Recycler.Adapter?

前端 未结 9 2112
执笔经年
执笔经年 2020-12-23 16:22

I am converting ListView of my app to RecyclerView. On ListView, it was very easy to implement OnClickListener but in RecyclerView, we have to do it in adapter. I want to op

相关标签:
9条回答
  • 2020-12-23 17:19

    I know this is too late for you but to anyone else who might see this.

    So instead of doing m vai did you can pass the context of the fragment when you first initialize your adapter.

    So in your constructor for your adapter you can add an argument like this

     // variable to hold fragment
     private Fragment fragment;
    
     public MyCustomAdapter(Fragment fragment)
     {
        this.fragment = fragment;
     }
    

    and in your fragment you can just initialize if like this

     MyCustomAdapter myAdapter = new MyCustomAdapter(this);
    

    finally you can call

    Fragment fragment = new myNewFragment();
    FragmentManager fragmentManager = context.getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment)
    .commit();
    

    so you can start a new fragment

    0 讨论(0)
  • 2020-12-23 17:21

    You just need an activity context passed in your constructor. Be sure to call new Adapter(this,...) from activities and new Adapter(getActivity(),...) from fragments.

    private Context context;
    
    @Override
    public void onClick(View v) {
        FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
    }
    
    0 讨论(0)
  • 2020-12-23 17:23

    in kotlin you can use this code:

        val fm : FragmentManager= (context as AppCompatActivity).supportFragmentManager
    
    0 讨论(0)
提交回复
热议问题