android中片段的参数化构造函数

use*_*095 -1 android android-fragments

我在片段中有以下构造函数:-

public PlaceDialogFragment(Place place, DisplayMetrics dm){
        super();
        this.mPlace = place;
        this.mMetrics = dm;
    }
Run Code Online (Sandbox Code Playgroud)

我也试过这个:-

public static final DialogFragment newInstance(Place place, DisplayMetrics dm)
{
    DialogFragment fragment = new DialogFragment();
    Bundle bundle = new Bundle(2);
    bundle.putParcelable("Place", place);
    bundle.putLong("Metrics", dm);
    fragment.setArguments(bundle);
    return fragment ;
}
Run Code Online (Sandbox Code Playgroud)

但是bundle.putLong("Metrics", dm) 网上有错误

Place是一个实现 Parceable 接口的类

但我收到一条错误消息:-

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
Run Code Online (Sandbox Code Playgroud)

任何建议如何解决这个问题?

Anu*_*kur 5

您应该使用默认构造函数并将参数作为包传递的原因是因为当系统恢复您的片段状态时,它会调用默认构造函数并恢复包。如果您从捆绑包中获取参数,则可以正确恢复状态。

使用您当前的方法,当重新创建片段时,您在自定义构造函数中所做的一切都将丢失。

有关示例,请参阅此答案