简体   繁体   中英

Trying to Open fragment from another fragment in android studio 3.5.3

I tried to open my second fragment from my 1st fragment but that giving me error. I tried as This answer and I google it everywhere done the same but not worked for me. I also tired with this android fragment transaction doc but didn't understand. Please can some one explain and solve this error in simpler way. Here is my code :

            FragmentManager fragmentManager=getActivity().getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.profile_f, new UProfileFragment()); //My second Fragment | & | home_layout is frame layout
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

and Here is my android studio screen error Screenshot :

图片 Screenshot of exact error

Edit : Thank you for your answers this problem was due to androidx library and old android library's code mix up. i was using the old app compact library instead of androidx library. i changed the fragment and function to androidx and it did work. Note for new Android developer: please use one compact library's code (either androidx or android old)

try this one code

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.home_layout, new ChatFragment(), "UProfileFragment"); //My second Fragment
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

As already suggested, use getSupportFragmentManager() AND make sure that your UProfileFragment inherits from androidx.fragment.app.Fragment in case you use AndroidX or android.support.v4.app.Fragment in case you don't.

Your Activity should inherit from AppCompatActivity

You forget to extend your UProfileFragment class with android.app.Fragment . Also, you should either use android.support.v4.app.Fragment or android.app.Fragment or androidx.fragment.app.Fragment if you are using AndroidX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM