Fragment的建構函式報錯
阿新 • • 發佈:2019-02-12
之前繼承Fragment時需要傳入幾個引數就想當然定義了一個帶參的構造方法 結果報錯了(媽賣批_(:з」∠)_) 像這樣 :
public class TestFragment extends Fragment { public TestFragment(String string){ } }
報錯原因:Fragment必須要有一個無參的構造方法 我過載了構造方法java就不會自動新增無參的構造方法了
大致就是說當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 publicView 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);}