ソースコードを見るとよくわかるね。
startActivityForResult の動作
Fragment
ActivityのstartActivityFromFragmentを呼んでます。
- /**
- * Call {@link Activity#startActivityForResult(Intent, int)} on the fragment's
- * containing Activity.
- */
- public void startActivityForResult(Intent intent, int requestCode) {
- if (mActivity == null) {
- throw new IllegalStateException("Fragment " + this + " not attached to Activity");
- }
- mActivity.startActivityFromFragment(this, intent, requestCode);
- }
FragmentActivity
requestCodeをビット演算させてActivityのsuper.startActivityForResultを呼んでます。
- /**
- * Called by Fragment.startActivityForResult() to implement its behavior.
- */
- public void startActivityFromFragment(Fragment fragment, Intent intent,
- int requestCode) {
- if (requestCode == -1) {
- super.startActivityForResult(intent, -1);
- return;
- }
- if ((requestCode&0xffff0000) != 0) {
- throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
- }
- super.startActivityForResult(intent, ((fragment.mIndex+1)<<16) + (requestCode&0xffff));
- }
onActivityResult の動作
FragmentActivity
requestCodeをビット演算でFragmentからstartActivityForResultActivityが実行されてるかチェックして、
FragmentのonActivityResultの呼び出しを制御しています。
- /**
- * Dispatch incoming result to the correct fragment.
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- int index = requestCode>>16;
- if (index != 0) {
- index--;
- if (mFragments.mActive == null || index < 0 || index >= mFragments.mActive.size()) {
- Log.w(TAG, "Activity result fragment index out of range: 0x"
- + Integer.toHexString(requestCode));
- return;
- }
- Fragment frag = mFragments.mActive.get(index);
- if (frag == null) {
- Log.w(TAG, "Activity result no fragment exists for index: 0x"
- + Integer.toHexString(requestCode));
- } else {
- frag.onActivityResult(requestCode&0xffff, resultCode, data);
- }
- return;
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
Fragment
- /**
- * Receive the result from a previous call to
- * {@link #startActivityForResult(Intent, int)}. This follows the
- * related Activity API as described there in
- * {@link Activity#onActivityResult(int, int, Intent)}.
- *
- * @param requestCode The integer request code originally supplied to
- * startActivityForResult(), allowing you to identify who this
- * result came from.
- * @param resultCode The integer result code returned by the child activity
- * through its setResult().
- * @param data An Intent, which can return result data to the caller
- * (various data can be attached to Intent "extras").
- */
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- }
Y.A.M の 雑記帳: Android Support Package の Fragment から startActivityForResult() を使うときの注意点