之前继承Fragment时需要传入几个参数就想当然定义了一个带参的构造方法 结果报错了(妈卖批_(:з」∠)_) 像这样 :
public class TestFragment extends Fragment { public TestFragment(String string){ } }
报错原因:Fragment必须要有一个无参的构造方法 我重载了构造方法java就不会自动添加无参的构造方法了
至于Fragment为什么须要无参构造方法看这篇文章:Fragment为什么须要无参构造方法
大致就是说当app被后台清理后我们从历史任务中再打开APP 安卓系统会调用Fragment的无参构造方法构造Fragment实例 不存在的话 就会出现闪退
解决方法:
不重载构造方法 通过Fragment.setArguments(Bundle bundle)来传递参数(官方推荐的)
private static final String BUNDLE_TITLE = "title"; public static VpFragment newInstance(String title){ Bundle bundle = new Bundle(); bundle.putString(BUNDLE_TITLE,title); VpFragment vpFragment = new VpFragment(); vpFragment.setArguments(bundle); return vpFragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { Bundle bundle = getArguments(); if (bundle != null){ String title = bundle.getString(BUNDLE_TITLE); } return super.onCreateView(inflater, container, savedInstanceState); }