android中Fragment的建構函式
阿新 • • 發佈:2019-01-26
最近在使用Fragment的過程中遇到一個問題,初步是想在Fragment中建立一個建構函式,建構函式中傳遞兩個自身需要的變數,如下
public class TestFragment extends Fragment { private String name; private String passwd; public TestFragment(String name, String passwd) { super(); this.name = name; this.passwd = passwd; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.main, null); return view; } }
結果eclipse報出兩個錯:
This fragment should provide a default constructor (a public constructor with no arguments) (com.example.TestFragment)
Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead
在增加一個空引數的建構函式可以消去第一個錯誤,但是第二個卻不能,第二個錯誤說要使用預設建構函式外加setArguments(Bundle)來代替,去android的官網上檢視Fragment的例子都是下面這個樣子的
CharSequence mLabel; /** * Create a new instance of MyFragment that will be initialized * with the given arguments. */ static MyFragment newInstance(CharSequence label) { MyFragment f = new MyFragment(); Bundle b = new Bundle(); b.putCharSequence("label", label); f.setArguments(b); return f; }
既然人家這麼寫例子肯定還是有道理的,我們只需要依葫蘆畫瓢就可以了,去掉帶參的建構函式,建立一個newInstance函式,如下
public class TestFragment extends Fragment
{
private String name;
private String passwd;
public static TestFragment newInstance(String name, string passwd) {
TestFragment newFragment = new TestFragment();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("passwd", passwd);
newFragment.setArguments(bundle);
return newFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.main, null);
return view;
}
}
如此這般,第二個錯誤就消失了,在Fragment所依賴的Activity中,用以下語句建立Fragment例項即可
Fragment testFragment=TestFragment.newInstance("name","passwd");
對於從Activity傳遞到Fragment中的引數我們只需要在Fragment的onCreate中獲取就可以了
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
name = args.getString("name");
passwd = args.getstring("passwd");
}
}