当试图重构构造函数时,比如:
<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>