Android: How to call Fragment class from activity using Intent

22,408

Solution 1

Fragment needs to be hosted by a FragmentActivity, you can't add a fragment via an Intent.

You need to create a FragmentManager to add your fragment in the FragmentActivity (or call another FragmentActivity via an Intent and add your fragment on it).
See this topic for more information: Add a Fragment to an Activity at Runtime.

Solution 2

            Fragment TargetFragment=new target_fragment();
            FragmentTransaction transaction=getFragmentManager().beginTransaction();
            transaction.replace(R.id.main_content,TargetFragment);
            transaction.addToBackStack(null);
            transaction.commit();
Share:
22,408
Rajeev Sahu
Author by

Rajeev Sahu

12+ years of experience in Software Industry. 7+ years of experience in Mobile Application Development with technical expertise on : Android, Kotlin, Core Java, SQLite, RxJava, XML/JSON, C/C++, VC++(MFC), Symbian C++, Qt/QML.

Updated on September 21, 2020

Comments

  • Rajeev Sahu
    Rajeev Sahu over 3 years

    I am trying to call a Fragment class from Activity using Intent. Is it possible to implement. Please provide your views.

  • Rajeev Sahu
    Rajeev Sahu about 10 years
    Thanks Fllo. I'll try this as you have mentioned.
  • Admin
    Admin over 9 years
    If change it to fragment activity fragment manager not working
  • Blo
    Blo over 9 years
    Because you maybe need to use getSupportFragmentManager instead, @Eddie.
  • André Kool
    André Kool over 7 years
    Please add some explenation to your answer. Only showing code can be confusing for some people.