原文地址: http://blog.sina.com.cn/s/blog_6f68c4d90102vb1i.html
在support v4中的fragment startActivityForResult时,必须使用this.startActivityForResult()而不是getActivity().startActivityForResult(),原因是v4的fragment.startActivityForResult()中,调用了startActivityFromFragment(),其中对requestCode做了处理,把requestCode的高16位指定fragment index,然后低16位用于原本的requestCode:
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));
}
在setResult()并finish()之后,FragmentActivity会检查requestCode是否包含fragment index,有则分发result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
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);
}
所以如果使用getActivity().startActivityForResult()的话,没有对requestCode进行处理,就不能正确得分发result了(跪) 。