android - 找不到 fragment 构造函数

标签 android android-fragments

我在某些设备上遇到了这个问题,并且在我的崩溃分析中遇到了错误。许多用户设备都面临这个问题,但在我的设备上它运行良好。

Unable to start activity ComponentInfo{com.ox.outloks.new/com.ox.outloks.new.activities.MainDrawerActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.alchemative.outfitters.outfitters.fragments.ProductsFragment: could not find Fragment constructor

错误出现在 Activity super.onCreate(savedInstanceState);

中的行
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

这是 ProductsFragment 的构造函数

@SuppressLint("ValidFragment")
public ProductsFragment(String id) {
    categoryID = id;
}

最佳答案

您创建的所有 Fragment必须有一个公共(public)的、无参数的构造函数。一般来说,最好的做法是根本不定义任何构造函数,而是依靠 Java 为您生成默认构造函数。但你也可以这样写:

public ProductsFragment() {
    // doesn't do anything special
}

如果您的 fragment 需要额外的信息,例如您发布的示例中的 String id,一个常见的模式是定义一个 newInstance() 静态“工厂方法”,它将使用参数 Bundle 以将该信息提供给您的 fragment 。

public static ProductsFragment newInstance(String id) {
    Bundle args = new Bundle();
    args.putString("id", id);
    ProductsFragment f = new ProductsFragment();
    f.setArguments(args);
    return f;
}

现在,您将调用 ProductsFragment.newInstance(id),而不是调用 new ProductsFragment(id)。并且,在您的 fragment 中,您可以通过调用 getArguments().getString("id") 访问 id。

通过利用参数包(而不是创建一个特殊的构造函数),您的 fragment 将能够被 Android 框架销毁和重新创建(例如,如果用户旋转他们的手机)并且您的必要信息(id)将保留.

关于android - 找不到 fragment 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831053/

相关文章:

android - firebase 远程配置的最短缓存过期时间是多少?

android - 为什么按下后退按钮时 addToBackStack 不起作用

android - fragment 无法转换为 android.support.v4.app.Fragment

android - 清除 fragment 中的操作栏

java - Android:获取N个推送通知

android - ListView 中没有弹性滚动

android - 如何实现拖动选择功能,如 Google Photos 应用中所示

android - 为每个 fragment 添加一个操作栏

android - ViewPager 和 Fragment — 存储 Fragment 状态的正确方法是什么?

java - OpenCV 和 OpenCL 之间的区别