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

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

问题描述

我在某些设备上遇到此问题,并且崩溃分析出现错误.许多用户设备都面临此问题,但是在我的设备上工作正常.

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片段.suitters.outfitters.fragments.ProductsFragment:找不到Fragment构造子

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;
}

现在,您将调用 ProductsFragment.newInstance(id),而不是调用 new ProductsFragment(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.

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

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