android – onActivityResult不在Fragment中调用
作者:互联网
应用程序的结构如下:
tabHost (in Activity) -> contains -> TabFragment(extend base container fragment)
1.活动中的代码:
tabHost.addTab(
tabHost.newTabSpec("home").setIndicator("",
getResources().getDrawable(R.drawable.btn_home)),
HomeFragment.class, null);
2. HomeFragment中的代码
(请注意,HomeFragment不是实际的函数,而是像这样的容器,它扩展了BaseContainerFragment):
public class HomeFragment extends BaseContainerFragment {
public Home homeFrag;
private boolean mIsViewInited;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.container_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
homeFrag = new Home();
replaceFragment(homeFrag, false);
}
}
3. BaseContainerFragment
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
}
public boolean popFragment() {
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
4.在Home(片段的实际内容)
UploadType fragment = new UploadType();
Bundle bundle = new Bundle();
bundle.putString("form_type", "request");
fragment.setArguments(bundle);
((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
5.在UploadType中,我调用相机活动,但onActivityResult仅在主活动中返回.
startActivityForResult(intent, REQUEST_CAMERA);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("test1", "result2");
super.onActivityResult(requestCode, resultCode, data);
}
如何在UploadType上触发onActivityResult?感谢帮助.
解决方法:
这不起作用的原因是因为您从嵌套片段中调用startActivityForResult(). Android足够聪明,可以将结果路由回Activity,甚至是片段,但不会将其路由到嵌套片段,因此您无法获得回调.
(更多信息为什么不起作用here或stackoverflow)
现在为了使其工作,我建议您手动将回调路由到ParentFragment(= BaseContainerFragment)中的ChildFragment(= UploadType):
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment uploadType = getChildFragmentManager().findFragmentById(R.id.container_framelayout);
if (uploadType != null) {
uploadType.onActivityResult(requestCode, resultCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
标签:onactivityresult,android,android-fragments,android-activity,android-tabhost 来源: https://codeday.me/bug/20190926/1819417.html