有关于Fragment是否应该有empty constructor的问题

http://stackoverflow.com/questions/10450348/do-fragments-really-need-an-empty-constructor?lq=1



147 down vote accepted

Yes they do.

You shouldn't really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

For example:

public static final AlertFragment newInstance(int title, String message) { AlertFragment f = new AlertFragment(); Bundle bdl = new Bundle(2); bdl.putInt(EXTRA_TITLE, title); bdl.putString(EXTRA_MESSAGE, message); f.setArguments(bdl); return f; }

And of course grabbing the args this way:

@Override public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... }

Then you would instantiate from your fragment manager like so:

public onCreate(Bundle savedInstanceState) { if(savedInstanceState == null){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content,AlertFragment.newInstance( R.string.alert_title, "Oh noes an error occured!") ) .commit(); } }

This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.


//--------------------------------自己--------------------------------

这个问题有时候在应用中崩溃,有时候又不崩溃,大部分的时候不会出现问题。


 
@SuppressLint("ValidFragment")


 
CheckinGuideFragment(id int) {

this.id = id;

}

如上述写法是不会报错的。运行的时候大部分时候正常,有时候就奔溃了。

(1)建议不要用这样子的构造函数;

(2)如果需要传递参数,建议使用newInstance()上面的方法。

147 down vote accepted

Yes they do.

You shouldn't really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

For example:

public static final AlertFragment newInstance(int title, String message) { AlertFragment f = new AlertFragment(); Bundle bdl = new Bundle(2); bdl.putInt(EXTRA_TITLE, title); bdl.putString(EXTRA_MESSAGE, message); f.setArguments(bdl); return f; }

And of course grabbing the args this way:

@Override public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... }

Then you would instantiate from your fragment manager like so:

public onCreate(Bundle savedInstanceState) { if(savedInstanceState == null){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content,AlertFragment.newInstance( R.string.alert_title, "Oh noes an error occured!") ) .commit(); } }

This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.

你可能感兴趣的:(有关于Fragment是否应该有empty constructor的问题)