Why OnCreate() of Activity and OnCreateView() of Fragment is not needed anymore…
From the day we commenced programming in android, we’ve been using setContentView
to inflate layouts in our Activity class. And when fragments were introduced, we’ve had to override onCreateView
and use a layout inflater to get our view from a layout ID. They feel a bit like boilerplate, right? So here's the solution to the problem
Activity
If we are using the OnCreate() method for just inflating the views then we can remove the OnCreate() method of the activity.
Previously :
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Now from AndroidX :
We can use the constructor which takes layout as a parameter. First, we need to define the dependency on our app build.gradle
file.
implementation 'androidx.appcompat:appcompat:1.1.0'
Then in the activity class.
class MainActivity : AppCompatActivity(R.layout.activity_main) {}
Note: We can access the views through Kotlin android extensions.
Tada, the layout is inflated.
Fragments
Previously :
OnCreateView() was called to inflate the view.
class MyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.my_fragment, container, false)
} override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val textView = view.findViewById(R.id.tv) as TextView
textView.text = "myText";
}
}
Note : onViewCreated
is only called if the view returned from onCreateView() is non-null.
Now from AndroidX :
We can use the constructor which takes layout as a parameter and eliminate the OnCreateView().
First, we need to define the dependency on our app build.gradle
file.
implementation 'androidx.appcompat:appcompat:1.1.0'
Then in the fragment class.
class MyFragment : Fragment(R.layout.my_fragment) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val textView = view.findViewById(R.id.tv) as TextView
textView.text = "myText";
}
}
Bam, the layout is inflated.
So get rid of these life cycle methods and keep the code clean 🙂