fadedbee
fadedbee

Reputation: 44745

Why are the onCreate methods of Android Views not just the constructors?

Android's onCreate methods seems to do all the things you would normally do in a constructor.

I have some code which programatically adds some views to a layout, and having an onCreate methods seems a little pointless - I only do it for consistency.

    for (Contact contact : manager.getContacts()) {
        GuiContact guiContact = new GuiContact(contact, this);
        guiContact.onCreate();

        // add them to the UI
        guiContact.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));
        contactListLayout.addView(guiContact);
    }

Why is this functionality in onCreate rather than in the constructors?

(There would be advantages relating to final members, if the functionality was in the constructors.)

Upvotes: 2

Views: 1214

Answers (1)

Rohan
Rohan

Reputation: 1190

It is because you never instantiate an Activity yourself. The system does it for you. And in order to do so, it needs a constructor without any parameters. So, it is better to do the initialization in onCreate().

Also, you set your Activitys layout in the onCreate() method, so getting a handle to that layout in the constructor will not work, and you will not be able to dynamically add views into it.

Upvotes: 5

Related Questions