Fragment建構函式和傳參
阿新 • • 發佈:2019-02-02
當試圖重構建構函式時,比如:
<span style="font-family:SimSun;font-size:18px;">public StudyFragment(String setHint){
}</span>
會提示如下錯誤:
Avoid non-default constructors in fragments: use a default constructor plus
Fragment#setArguments(Bundle)
instead
less... (Ctrl+F1)
From the Fragment documentation:
Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called
when the fragment is re-instantiated; instead, arguments can be supplied by the caller with
setArguments(Bundle)
and later retrieved by the Fragment with
getArguments()
.
推薦的方法是將要傳入的引數置於Bundle中,通過getArguments()傳入Bundle,比如:
<span style="font-family:SimSun;">public static StudyFragment newInstance(String setHint){ StudyFragment studyFragment = new StudyFragment(); Bundle bundle = new Bundle(); bundle.putString("TAG", setHint); studyFragment.setArguments(bundle); return studyFragment; }</span>
在Fragment的onCreate()或者onCreateView()等方法中通過Bundle使用傳入的引數:
Bundle bundle = getArguments();
if(bundle != null){
editText.setHint(bundle.getString(mTAG));
}
需要注意的是newInstance需要是static,否則在如下呼叫時會報錯:
<span style="font-family:SimSun;">StudyFragment studyFragment = StudyFragment.newInstance("hello");</span>
錯誤提示:Non-static method 'newInstance(java.lang.String)' cannot be referenced from a static context