Create new fragment kotlin
Here is an example of how to create a new fragment in Kotlin:
Step 1: Create a new Kotlin class
In your Android project, create a new Kotlin class by going to File
> New
> Kotlin Class
and name it, for example, MyFragment
.
Step 2: Extend the Fragment class
In the MyFragment
class, extend the Fragment
class:
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class MyFragment : Fragment() {
//...
}
Step 3: Override the onCreateView method
Override the onCreateView
method to inflate your fragment's layout:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.my_fragment_layout, container, false)
return view
}
In this example, we're inflating a layout file named my_fragment_layout.xml
and returning the inflated view.
Step 4: Add any additional code
You can add any additional code you need to your fragment, such as setting up views, handling events, or communicating with the activity.
Step 5: Register the fragment in your activity
In your activity, you need to register the fragment in the onCreate
method:
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragment = MyFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.fragment_container, fragment)
transaction.commit()
}
}
In this example, we're creating an instance of MyFragment
and adding it to the fragment container in our activity.
That's it! You've created a new fragment in Kotlin.