我在项目中发现了以下代码(变量/类名已更改):
private FragmentParams params;
public static MyFragment newInstance(FragmentParams params) {
MyFragment fragment = new MyFragment();
fragment.params = params; // <- Manually setting params in fragment class
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
ButterKnife.bind(this, view);
/* The following line initializes a class responsible for the user
interface. The params are used for that purpose. However, out of
nowhere, the params where null 2 times.*/
presenter.setParams(params);
return view;
}
该项目已经存在了几个星期,当NullPointerException
访问了参数时(在代码中更进一步),报告了一对presenter
。
我知道正确的方法是使用setArguments()
,但我想问的问题是:尖锐的线条是否有问题?
我唯一能想到的是,Android出于某种原因重新创建了片段,params
由于方法null
未被调用而成为newInstance
,因此,{{ 1}}未设置。
答案 0 :(得分:0)
您还可以尝试将片段保留实例状态设置为true,每当活动重新创建时,它都会将Fragment的实例保留在片段管理器中。
https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
答案 1 :(得分:0)
是的,它可能会有问题,因为重新创建活动时参数值会丢失。你可以做的是每次通过onSaveInstanceState销毁活动时保存参数值。可以看到示例here