Search code examples
androidandroid-fragmentsandroid-activityandroidx

Question about defining resource layout id in the activity/fragment constructor


I keep reading everywhere that you can now use the activity/fragment constructor to define the layout id with AndroidX, but none answer my question.

What if you have others things to do in Activity's onCreate or Fragment's onCreateView ? Can you still use this new constructor ?


Solution

  • For Activities

    Yes, it just means that the Activity will call setContentView() with the layout ID you provide as part of calling super.onCreate(savedInstanceState). Otherwise, you can proceed as normal in your onCreate().

    For Fragments

    Generally, if using the layout ID constructor, you'd want to move your code from onCreateView() to onViewCreated(), which is passed the View that was created by onCreateView().

    Of course, if you do want to override onCreateView() for some reason, you'd want to call super.onCreateView() to retrieve the inflated layout corresponding with the layout ID you provided to the constructor argument.