在fragment向activity传值时需要使用onAttach方法,由于onAttach(activity,Activity):void已被弃用,只能用onAttach(contex,Contex):void,但是在API<23时并不会去调用此方法,即会导致程序崩溃(此为google一个bug)。
解决方法有3个:
1.Using getSupportFragmentManager() will force you to use a Fragment from the support lib. So the first solution is to replace all fragments with the fragment from support lib and using getSupportFragmentManager().
使用 getSupportFragmentManager() 会强行使用该 support lib 里的Fragment, 所以通过使用getSupportFragmentManager()把所有原Fragment都替换成support lib 里的Fragment.
2.Solution that I've already implemented is to handle 2 possibilities
“我”已经亲测能处理这两种情况(应用是在API<23下运行或在API>=23下运行(Ps:这不是所有API下吗)。in my implementation I have a base class for all fragments from the project and I added this code there在我的实现办法中我在项目中为所有的frament建立了一个基础类,这里上码:
/*
* onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated
* Use onAttachToContext instead
*/
@TargetApi(23)
@Override
public void onAttach(Context context) {
super.onAttach(context);
onAttachToContext(context);
}
/*
* Deprecated on API 23
* Use onAttachToContext instead
*/
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
onAttachToContext(activity);
}
}
/*
* Called when the fragment attaches to the context
*/
protected void onAttachToContext(Context context) {
}
onAttach(Context context)
do nothing on Android M, just called the old method.----
Tony Zhang
@SuppressWarnings("deprecation")
在onAttach(activity,Activity):void上加上此申明便可任性使用,亲测完美解决本鸟的程序崩溃。感谢两位答主。