Android中两个类让你再也不用实现onActivityResult()
前言
当我们知道fragment仅仅可以收到自己请求的回调后,我们就可以用它来解耦activity中onActivityResult的逻辑了。一般情况下,如果一个activity中多个回调结果的话,onActivityResult()中会有各种case判断,并且这种设计也打断了流式写法。那么我们索性建立一个无UI的fragment做精准的接收器,这样就可以再也不写onActivityResult()了。
Fragment:
/** *@authorKale *@date2018/4/13 */ publicclassOnActResultEventDispatcherFragmentextendsFragment{ publicstaticfinalStringTAG="on_act_result_event_dispatcher"; privateSparseArraymCallbacks=newSparseArray<>(); @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setRetainInstance(true); } publicvoidstartForResult(Intentintent,ActResultRequest.Callbackcallback){ mCallbacks.put(callback.hashCode(),callback); startActivityForResult(intent,callback.hashCode()); } @Override publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata){ super.onActivityResult(requestCode,resultCode,data); ActResultRequest.Callbackcallback=mCallbacks.get(requestCode); mCallbacks.remove(requestCode); if(callback!=null){ callback.onActivityResult(resultCode,data); } } }
请求封装类:
publicclassActResultRequest{ privateOnActResultEventDispatcherFragmentfragment; publicActResultRequest(Activityactivity){ fragment=getEventDispatchFragment(activity); } privateOnActResultEventDispatcherFragmentgetEventDispatchFragment(Activityactivity){ finalFragmentManagerfragmentManager=activity.getFragmentManager(); OnActResultEventDispatcherFragmentfragment=findEventDispatchFragment(fragmentManager); if(fragment==null){ fragment=newOnActResultEventDispatcherFragment(); fragmentManager .beginTransaction() .add(fragment,OnActResultEventDispatcherFragment.TAG) .commitAllowingStateLoss(); fragmentManager.executePendingTransactions(); } returnfragment; } privateOnActResultEventDispatcherFragmentfindEventDispatchFragment(FragmentManagermanager){ return(OnActResultEventDispatcherFragment)manager.findFragmentByTag(OnActResultEventDispatcherFragment.TAG); } publicvoidstartForResult(Intentintent,Callbackcallback){ fragment.startForResult(intent,callback); } publicinterfaceCallback{ voidonActivityResult(intresultCode,Intentdata); } }
发送请求和监听请求的代码:
Intentintent=newIntent(this,SecondActivity.class); request.startForResult(intent,newActResultRequest.Callback(){ @Override publicvoidonActivityResult(intresultCode,Intentdata){ Toast.makeText(MainActivity.this,""+resultCode,Toast.LENGTH_SHORT).show(); } });
题外话:
最新的support包已经解决了fragment嵌套时里层的fragment收不到结果的问题,请及时更新依赖。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。