【问题标题】:Confused, where is onCreateView method in MainActivity?迷茫了,MainActivity的onCreateView方法在哪里?
【发布时间】:2016-06-17 12:02:37
【问题描述】:

我遵循了有关如何创建 android 应用程序的在线教程。 我想在 onCreateView 中分配变量,但是方法在哪里? 我正在使用 androidstudio 最新的顺便说一句。 请帮忙

【问题讨论】:

  • Activity 是一个 View 容器,而不是 View 本身。这就是为什么你会在 Fragment 中找到它的方法,而不是在 Activity 中。
  • @BobMalooga Activity 不是视图容器,Fragment 也不是。并且常规视图没有onCreateView()
  • 如果您在 Google.com 上搜索而不是在此处发布,您可能会在不投反对票的情况下得到答案。

标签: java android


【解决方案1】:

对于 Activity,等效方法是 onCreate()。您可以在 Fragment 中覆盖 onCreateView()

【讨论】:

  • 但是在教程中,onCreateView在MainActivity.java中,这是为什么呢?
  • 活动有一个 oncreateViewMethod,但它是支持库的一部分,用于在 Honeycomb 上启用 v11 API。你今天不应该再使用它了。
  • 什么..??哦,我明白了
  • 也许他们使用了内部类 Fragment?无论哪种方式,您都不能从您的活动中调用 onCreateView。要么使用 onCreate() 要么在你的片段中使用它。
【解决方案2】:

onCreateView 是 Fragment 的方法,而不是 Activity。

如图documentation

onCreateView(LayoutInflater, ViewGroup, Bundle) 创建并返回与 fragment 关联的视图层次结构。

【讨论】:

  • 但是在教程中,onCreateView在MainActivity.java中,这是为什么呢?
  • 可能是使用的内部类。
  • MainActivity 中搜索class PlaceholderFragment。我认为onCreateView 是名为PlaceholderFragment 的内部类的方法。
【解决方案3】:

困惑,MainActivity 中的 onCreateView 方法在哪里?

无处可去。 Activity 没有这个方法(它是 Fragment 的)。请改用onCreate()

【讨论】:

  • 看起来像内部 Fragment 类。这不是一个好的做法,所以要小心,因为本教程可能会教给你错误的东西。
【解决方案4】:

在活动中创建方法是

 protected void onCreate(Bundle savedInstanceState) {}

Fragment 中的创建方法是

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2014-06-19
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多