Load fragments inside fragment in Kotlin

I have an app structure in mind:

DashBoard Activity

  • HomeFragment
    • AdsFragment
    • GreetingFragment
    • ExperienceFragment

WIth that in mind, I'm trying to load different fragments in HomeFragment, which is also a fragment

I've written the following code in HomeFragment's onCreateView()

val fm : FragmentManager = childFragmentManager
        val container = R.id.greetingFragmentContainer
        val greetingFragment : Fragment? = fm.findFragmentById(R.id.fragmentGreeting)
        if (greetingFragment != null) {
            fm.beginTransaction().replace(container, greetingFragment).commit()
        } else {
            Log.e("HomeFragment", "Fragment not found")
        }

fragment_greeting.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/fragmentGreeting"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="._fragments.dash.GreetingFragment">

    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:src="@drawable/loading"/>

</FrameLayout>

Using that if statement, I found out that the greetingFragment value was returning null.

What am I doing wrong?


try this in your HomeFragment

lateinit var context: AppCompatActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.context = context as AppCompatActivity
    }

and call the fragment without findFragmentbyId like below:

 val fm = context.supportFragmentManager
            val fragmentTransaction: FragmentTransaction
            val fragment = GreetingFragment()
            fragmentTransaction = fm.beginTransaction()
            fragmentTransaction.replace(R.id.container, fragment)
                .addToBackStack(null)
            fragmentTransaction.commit()

Load fragments inside fragment in Kotlin, This lyout is inside the father fragment of course. Here is an example. create a kotlin file let's say **”util.kt”** and add this piece of code. Select File > New > Fragment > Fragment (Blank). For the fragment name, use TitleFragment . Clear all the checkboxes, including create Layout XML , include fragment factory methods , and include


Home fragment should contain three framelayouts for loading AdsFragment, Greetings Fragment,Experience Fragment. Fragment can be loaded to frame layouts using child fragment manager.

Android Kotlin Fragment inside a Fragmet | by Dina TAKLIT, Inside of an app which uses fragments extensively, we need to keep in mind that There are two ways to add a fragment to an activity: dynamically using Java� You can do it with 2 ways, First Create a class and extended with Fragment class and create resource layout file. OR. Second ways is Right Click on Package -> New -> Fragment -> Fragments (Blank) then give Fragment Name , check Fragment Layout Name – > Finish


There are multiple ways to instantiate the fragments. The method you are using doesn't do anything except just declaring a layout, which is not what you want! Use the following approach to do it correctly.

<LinearLayout>
 <fragment android:id="@+id/ad" android:name="._fragments.dash.AdFragment" />
<fragment android:id="@+id/greeting" android:name="._fragments.dash.GreetingFragment"/>
<fragment android:id="@+id/experience" android:name="._fragments.dash.ExpFragment"/>
</LinearLayout>

Here, the classes specified in android:name refer to dedicated fragments classes extending the Fragment class. You need to specify the each fragment's layout in dedicated layout resource e.g. R.layout.ad_fragment, R.layout.greeting_fragment and R.layout.exp_fragment, which must be inflated inside onCreateView() function of every Class.

Please refer to Official Android documentation for more information.

Android Fragments Tutorial: An Introduction with Kotlin , When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its� For each fragment in your app, the Safe Args plugin generates a corresponding NavDirection class. You add the NavDirection class to the fragment code, then use the class to pass arguments between the fragment and other fragments. The NavDirection classes represent navigation from all the app's actions. Implicit intents:


To load different fragment in same view i did this.

    private val manager = supportFragmentManager

When you have to load each of fragments ( don't think you have to show all of them on same time) you can do this

    val transaction = manager.beginTransaction()
    val fragment = FragmentOne()
    transaction.replace(R.id.fragment_holder, fragment)
    transaction.addToBackStack(null)
    transaction.commit()

Good practise would be have a general when statment listening different buttons tapu and then instatiante different fragment, because make different buttons would create more copy code.

 override fun onOptionsItemSelected(item: MenuItem): Boolean {

    val fragment = when(item.itemId) {
        R.id.ads_menu -> FragmentAds()
        R.id.grets_menu -> FragmentGreeting()
        R.id.exp_menu -> FragmentExperience()
        else ->  return super.onOptionsItemSelected(item)
    }

    val transaction= manager.beginTransaction()
    transaction.replace(R.id.fragment_holder, fragment)
    transaction.addToBackStack(null)
    transaction.commit()
    return true
}

Of course there are three fragment class that have their layout and override all methods. I try this also in profiler and it seems that.

The issue (if we can call like this) about this solution is that on back pressed all history of fragments is loaded, because replace remove and add a new one.

To avoid it, all fragments could be all visible and changing button just change the selected one but of course it complicated the when statment.

ft = fm.beginTransaction();
ft.hide(getFragmentManager().findFragmentByTag("searchFragment"));
ft.add(R.id.main_fragment, yourDetailfragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();

Creating and Using Fragments, Add a Fragment to an Activity at Runtime; Replace One Fragment with Rather than defining the fragments for an activity in the layout file—as shown in the Inside your activity, call getSupportFragmentManager() to get a Kotlin Java More. 2.2 Create Fragment Pages to be used in the viewPager. In this application, we will use three pages in viewPager. So, we need to create three fragment and it’s xml file. Below are the three fragments name that we are going to create now. (1) FirstFragment.java and first_fragment.xml file (2) SecondFragment.java and second_fragment.xml file


Fragments, All the course codelabs are listed on the Android Kotlin Fundamentals codelabs landing page. In this codelab, you learn about fragments, and you create a fragment inside a starter app called How to add a Fragment statically to your app� Image Source: Kotlin on Android Originally posted as an answer to a StackOverflow question.. Before going to the Kotlin way, let’s recap how we used to add a Fragment in Java. The naive way:


Build a flexible UI, In the fragment app example we add fragments to the activity layout in two different ways: specifying a fragment in the XML file using inside the activity's layout� Android RecyclerView in Fragment (Kotlin) February 27, 2019. android Android Load FirestoreUI FirestoreRecyclerAdapter With Empty Query (Clear RecyclerView)


Android Kotlin Fundamentals 03.1: Create a fragment, to add a TextView to the fragment layout as follows: From the resulting menu, select the New -> Kotlin� You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup.