Hammad Hassan
Hammad Hassan

Reputation: 91

How to load a fragment on button click in Kotlin?

Below is a picture of a "practice" application that I am working on. I want to swipe the fragment (which is in the middle in gray color) with second fragment that I have, on the click of a "next button". How can I "load" another fragment on button click in Android, using Kotlin?

A picture of application, for better understanding of a problem

Upvotes: 1

Views: 6880

Answers (2)

akshay_shahane
akshay_shahane

Reputation: 4643

you can declare inline function like this

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
    val fragmentTransaction = beginTransaction()
    fragmentTransaction.func()
    fragmentTransaction.commit()
} 

use it like ( this goes in your button click listener)

supportFragmentManager.inTransaction {
    add(R.id.frameLayoutContent, fragment)
}

Upvotes: 1

Victor Cold
Victor Cold

Reputation: 653

If next button ID in the layout is "next" then you can make it like this:

val fragment = NextFragment()
next.setOnClickListener {
    supportFragmentManager.beginTransaction().replace(R.id.fragmentContainer, fragment).commit()
    }

Where "fragmentContainer" (which is FrameLayout view) is the layout ID of the container where your fragments will be placed.

Upvotes: 2

Related Questions