找不到片段构造函数 [英] Could not find Fragment constructor

查看:37
本文介绍了找不到片段构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am facing the issue on some devices and getting an error on my crash analytics. A lot of user devices are facing this issue, but on my device it's working fine.

无法启动活动 ComponentInfo{com.ox.outloks.new/com.ox.outloks.new.activities.MainDrawerActivity}:android.support.v4.app.Fragment$InstantiationException:无法实例化片段 com.alchemative.Outfitters.outfitters.fragments.ProductsFragment:找不到片段构造函数

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

错误发生在活动 super.onCreate(savedInstanceState);

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

这是 ProductsFragment 构造函数

Here is ProductsFragment constructor

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

推荐答案

您创建的所有 Fragment必须具有公共的无参数构造函数.通常,最佳实践是根本不要定义任何构造函数,而是依靠 Java 为您生成默认构造函数.但是你也可以这样写:

All Fragment classes you create must have a public, no-arg constructor. In general, the best practice is to simply never define any constructors at all and rely on Java to generate the default constructor for you. But you could also write something like this:

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

如果你的片段需要额外的信息,比如你发布的例子中的 String id,一个常见的模式是定义一个 newInstance() 静态工厂方法",它将使用参数 Bundle 将该信息提供给您的片段.

If your fragment needs extra information, like String id in your posted example, a common pattern is to define a newInstance() static "factory method" that will use the arguments Bundle to give that info to your fragment.

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

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

Now, rather than calling new ProductsFragment(id), you'll call ProductsFragment.newInstance(id). And, inside your fragment, you can access the id by calling getArguments().getString("id").

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

By leveraging the arguments bundle (instead of creating a special constructor), your fragment will be able to be destroyed and recreated by the Android framework (e.g. if the user rotates their phone) and your necessary info (the id) will persist.

这篇关于找不到片段构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆