为什么 Android 视图的 onCreate 方法不仅仅是构造函数?
Why are the onCreate methods of Android Views not just the constructors?
Android 的 onCreate
方法似乎可以完成您通常在构造函数中执行的所有操作。
我有一些代码以编程方式向布局添加一些视图,并且使用 onCreate
方法似乎有点毫无意义 - 我这样做只是为了保持一致性。
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);
}
为什么这个功能在 onCreate
而不是在构造函数中?
(如果功能在构造函数中,那么 final
成员会有优势。)
这是因为你从来没有自己实例化一个Activity
。系统为你做。为此,它需要一个不带任何参数的构造函数。因此,最好在 onCreate()
.
中进行初始化
此外,您在 onCreate()
方法中设置了 Activity
s 布局,因此在构造函数中获取该布局的句柄将不起作用,并且您将无法动态添加视图进去。
Android 的 onCreate
方法似乎可以完成您通常在构造函数中执行的所有操作。
我有一些代码以编程方式向布局添加一些视图,并且使用 onCreate
方法似乎有点毫无意义 - 我这样做只是为了保持一致性。
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);
}
为什么这个功能在 onCreate
而不是在构造函数中?
(如果功能在构造函数中,那么 final
成员会有优势。)
这是因为你从来没有自己实例化一个Activity
。系统为你做。为此,它需要一个不带任何参数的构造函数。因此,最好在 onCreate()
.
此外,您在 onCreate()
方法中设置了 Activity
s 布局,因此在构造函数中获取该布局的句柄将不起作用,并且您将无法动态添加视图进去。