Android replace the current fragment with another fragment

前端 未结 6 1332
迷失自我
迷失自我 2020-11-28 09:23

I just started with fragment design for HoneyComb. I created two fragments. When i click a button in the left side fragment, a new fragment is created in right side. Meanwh

6条回答
  •  忘掉有多难
    2020-11-28 09:53

    Latest Stuff

    Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

    Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

    1. Add Kotlin extension for Fragments to your project.

    In your app level build.gradle file add the following,

    dependencies {
        def fragment_version = "1.2.5"
    
        // Kotlin
        implementation "androidx.fragment:fragment-ktx:$fragment_version"
        // Testing Fragments in Isolation
        debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
    }
    
    1. Then simple code to replace the fragment,

    In your activity

    supportFragmentManager.commit {
        replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
        addToBackStack(null)
    }
    

    References

    Check latest version of Fragment extension

    More on Fragments

提交回复
热议问题