【问题标题】:Class extending Fragment - error says make sure class name exists, is public, and has an empty constructor that is public类扩展片段 - 错误说确保类名存在,是公共的,并且有一个公共的空构造函数
【发布时间】:2013-10-15 06:34:51
【问题描述】:

我有这样的课:

class TopicFragment extends Fragment{

public TopicFragment(VO vO) { 
    // some code
    }

}

用户报告应用程序崩溃并且日志显示:

 android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.aaa.wert.TopicFragment: make sure class name exists, is public, and has an empty constructor that is public

我已经查看了这个链接,但我无法解决这个问题;

Do fragments really need an empty constructor?

Fragment - InstantiationException: no empty Constructor -> Google Maps v2?

请帮帮我。

【问题讨论】:

  • 您也应该发布实例化此片段的代码。还有,为什么 TopicFragment 本身不公开?
  • 好吧,首先,改变你的片段构造函数,让它为空,也没有参数。然后将 TopicFragment 设置为 public。然后,请发布您的完整代码。

标签: android android-fragments fragment


【解决方案1】:

只需添加一个没有参数的空构造函数,它是公共的。如果您在 XML 中设置了没有空构造函数的片段,则无法创建它。

public TopicFragment() {
}

我通常也总是只有空的构造函数,并且有一个这样的方法来实例化参数

public static TopicFragment newInstance(VO vo) {
    TopicFragment fragment = new TopicFragment();
    fragment.setVo(vo);
    return fragment;
}

编辑:正如那些在 cmets 中所说的那样,让你上课:

public class TopicFragment {
}

【讨论】:

  • 那么我需要将以上两个都添加到我的班级吗?
  • 您需要添加第一个,如果您愿意,可以使用第二个代替您的。这完全取决于您对第二个感到满意。
  • 我添加了默认构造函数,它说避免在片段中使用非默认构造函数:使用默认构造函数加上 Fragment#setArguments(Bundle) 代替
  • 您拥有的是非默认构造函数。建议按照我在示例中向您展示的操作并摆脱您的构造函数。
  • 文档声明您应该使用 setArguments(Bundle) developer.android.com/reference/android/app/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多