Could not find Fragment constructor

前端 未结 3 1427
谎友^
谎友^ 2020-12-23 19:25

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.

3条回答
  •  粉色の甜心
    2020-12-23 19:29

    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
    }
    

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

    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").

    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.

提交回复
热议问题