【问题标题】:I have added empty constructor in Fragment. but still "make sure class name exists, is public, and has an empty constructor that is public"我在 Fragment 中添加了空构造函数。但仍然“确保类名存在,是公共的,并且有一个公共的空构造函数”
【发布时间】:2014-05-13 15:58:48
【问题描述】:

我有一个问题。 我正在使用 Fragment 编写一些帮助页面。

public HelpFragment(int i) {
            Bundle args = new Bundle();
            args.putInt("page", i);
            setArguments(args);
        }

在测试用例中,我得到了这个错误。

“确保类名存在,是公开的,并且有一个公开的空构造函数”

所以,我添加了空构造函数。

public HelpFragment() {
            Bundle args = new Bundle();
            args.putInt("page", 0);
            setArguments(args);
        }

但仍然会产生该错误。 我该怎么办? 提前致谢。

【问题讨论】:

  • 这个错误并不总是产生。很少复制。
  • 也发布您的类声明,即public (static) class HelpFragment extends Fragment 以及它在您的代码中的位置(例如,如果它是一个内部类)。

标签: android android-fragments


【解决方案1】:

根本不要重写构造函数。而是创建公共静态方法:

public static HelpFragment newInstance(int i) {
    HelpFragment f = new HelpFragment();
    Bundle args = new Bundle();
    args.putInt("page", i);
    f.setArguments(args);
    return f;
}

【讨论】:

  • 嗨,LR89。你能告诉我为什么构造函数应该是静态的吗?据我所知,静态内部类用于性能。所以我认为让内部类静态是没有必要的。
  • 这不是构造函数,而是一种方法,它提供了在不覆盖构造函数的情况下将参数传递给片段的能力。为什么我们不能简单地覆盖构造函数?检查这个答案stackoverflow.com/a/10450535/3519587为什么这个方法是静态的?因为……为什么不呢?它与对象实例无关,因此无需使其成为非静态的。
【解决方案2】:

你如何将你的片段调用到你的应用程序中?如果您使用片段,我认为您不应该覆盖构造函数,并将您的参数放在 onCreate 或 onCreateView 中

如果你使用片段,我认为 onCreateView 更好

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //your arguments here
    return inflater.inflate(R.layout.fragment_help_layout, container, false);
}

【讨论】:

  • 我已经在代码中有 onCreateView()。在正常情况下,此代码正常工作。对不起,你的想法不正确。在 Stackoverflow.com 中搜索的结果,这个错误是关于 Fragment 的构造函数和 newInstance() 方法的。
【解决方案3】:

我完全傻了。 我一直错过在代码中添加这个。

super()

但我并不 100% 相信这个解决方案。 如果我在 Google Play 崩溃中看到此错误,我会报告。

【讨论】:

  • 你最好像 LR89 说的那样做,接受他的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
  • 2011-02-08
  • 2011-03-01
相关资源
最近更新 更多