Welcome to this in-depth guide on Kotlin Activities and Fragments! By the end of this lesson, you'll have a solid understanding of these fundamental building blocks for Android app development. Let's dive in!
Activities and Fragments are essential components in Android app development using Kotlin.
By learning Activities and Fragments, you'll be able to create more modular, reusable, and maintainable Android applications.
Let's create a simple Activity that displays a welcome message.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.textView).text = "Welcome to your first Kotlin Activity!"
}
}š Note: This Activity inflates a layout (activity_main.xml) and sets the welcome message to a TextView.
onCreate method do? š”What does the `onCreate` method do in an Activity?
Fragments allow you to create modular and reusable pieces of an Activity's UI. Here's an example of a simple Fragment:
class WelcomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_welcome, container, false)
view.findViewById<TextView>(R.id.textView).text = "Welcome to your first Kotlin Fragment!"
return view
}
}š Note: This Fragment inflates a layout (fragment_welcome.xml) and sets the welcome message to a TextView.
To communicate between an Activity and a Fragment, you can define interfaces and implement them in both parts.
What is the benefit of using Fragments in Android development?
That's it for this introduction to Kotlin Activities and Fragments! Keep practicing, and you'll be creating amazing Android apps in no time. š Happy coding!