您好,登錄后才能下訂單哦!
前言
當我們知道fragment僅僅可以收到自己請求的回調后,我們就可以用它來解耦activity中onActivityResult的邏輯了。一般情況下,如果一個activity中多個回調結果的話,onActivityResult()中會有各種case判斷,并且這種設計也打斷了流式寫法。那么我們索性建立一個無UI的fragment做精準的接收器,這樣就可以再也不寫onActivityResult()了。
Fragment:
/** * @author Kale * @date 2018/4/13 */ public class OnActResultEventDispatcherFragment extends Fragment { public static final String TAG = "on_act_result_event_dispatcher"; private SparseArray<ActResultRequest.Callback> mCallbacks = new SparseArray<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } public void startForResult(Intent intent, ActResultRequest.Callback callback) { mCallbacks.put(callback.hashCode(), callback); startActivityForResult(intent, callback.hashCode()); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ActResultRequest.Callback callback = mCallbacks.get(requestCode); mCallbacks.remove(requestCode); if (callback != null) { callback.onActivityResult(resultCode, data); } } }
請求封裝類:
public class ActResultRequest { private OnActResultEventDispatcherFragment fragment; public ActResultRequest(Activity activity) { fragment = getEventDispatchFragment(activity); } private OnActResultEventDispatcherFragment getEventDispatchFragment(Activity activity) { final FragmentManager fragmentManager = activity.getFragmentManager(); OnActResultEventDispatcherFragment fragment = findEventDispatchFragment(fragmentManager); if (fragment == null) { fragment = new OnActResultEventDispatcherFragment(); fragmentManager .beginTransaction() .add(fragment, OnActResultEventDispatcherFragment.TAG) .commitAllowingStateLoss(); fragmentManager.executePendingTransactions(); } return fragment; } private OnActResultEventDispatcherFragment findEventDispatchFragment(FragmentManager manager) { return (OnActResultEventDispatcherFragment) manager.findFragmentByTag(OnActResultEventDispatcherFragment.TAG); } public void startForResult(Intent intent, Callback callback) { fragment.startForResult(intent, callback); } public interface Callback { void onActivityResult(int resultCode, Intent data); } }
發送請求和監聽請求的代碼:
Intent intent = new Intent(this, SecondActivity.class); request.startForResult(intent, new ActResultRequest.Callback() { @Override public void onActivityResult(int resultCode, Intent data) { Toast.makeText(MainActivity.this, "" + resultCode, Toast.LENGTH_SHORT).show(); } });
題外話:
最新的support包已經解決了fragment嵌套時里層的fragment收不到結果的問題,請及時更新依賴。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。