Android中Fragment的構造函數 his fragment should provide a default constructor

Android中Fragment的構造函數 his fragment should provide a default constructor。最近在使用Fragment的過程中遇到一個問題,初步是想在Fragment中創建一個構造函數,構造函數中傳遞兩個自身需要的變量,如下

publicclassTestFragmentextendsFragment

{

privateStringname;

privateStringpasswd;

publicTestFragment(Stringname,Stringpasswd)

{

super();

this.name=name;

this.passwd=passwd;

}

@Override

publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,

BundlesavedInstanceState){

//TODOAuto-generatedmethodstub

Viewview=inflater.inflate(R.layout.main,null);

returnview;

}

}

結果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的例子都是下面這個樣子的

CharSequencemLabel;

/**

*CreateanewinstanceofMyFragmentthatwillbeinitialized

*withthegivenarguments.

*/

staticMyFragmentnewInstance(CharSequencelabel){

MyFragmentf=newMyFragment();

Bundleb=newBundle();

b.putCharSequence("label",label);

f.setArguments(b);

returnf;

}

既然人傢這麼寫例子肯定還是有道理的,我們隻需要依葫蘆畫瓢就可以瞭,去掉帶參的構造函數,創建一個newInstance函數,如下[java]view plaincopy

publicclassTestFragmentextendsFragment

{

privateStringname;

privateStringpasswd;

publicstaticTestFragmentnewInstance(Stringname,stringpasswd){

TestFragmentnewFragment=newTestFragment();

Bundlebundle=newBundle();

bundle.putString("name",name);

bundle.putString("passwd",passwd);

newFragment.setArguments(bundle);

returnnewFragment;

}

@Override

publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,

BundlesavedInstanceState){

//TODOAuto-generatedmethodstub

Viewview=inflater.inflate(R.layout.main,null);

returnview;

}

}

如此這般,第二個錯誤就消失瞭,在Fragment所依賴的Activity中,用以下語句創建Fragment實例即可

FragmenttestFragment=TestFragment.newInstance("name","passwd");

對於從Activity傳遞到Fragment中的參數我們隻需要在Fragment的onCreate中獲取就可以瞭

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

Bundleargs=getArguments();

if(args!=null){

name=args.getString("name");

passwd=args.getstring("passwd");

}

}

You May Also Like