我有一个活动,其中包含BottomNavigationView
和NavHostFragment
。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.navigation_profile);
NavController navController = Navigation.findNavController(this, R.id.myNavHostFragment);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
我还在此父级活动中添加了onActivityResult
方法。
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(this,"Parent onActivity",Toast.LENGTH_SHORT).show();
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
在片段中,我有一个ImageView
,我正在其中使用Intent从用户那里选择图像。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
this.startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
在片段的onActivityResult
中,我正在这样做:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
Toast.makeText(getActivity(),"OnActivityResult",Toast.LENGTH_SHORT).show();
// Result returned from launching the Intent to select image for profile
if (requestCode == RC_PHOTO_PICKER && resultCode == Activity.RESULT_OK) {
Toast.makeText(getActivity(),"Called",Toast.LENGTH_SHORT).show();
}
}
问题是onActivityResult
既不在父活动中也不在片段中被调用。
答案 0 :(得分:1)
您不能将Intent.createChooser()
与Intent.GET_CONTENT
一起使用-这对于活动和片段都是正确的。
相反,只需将您的Intent直接用于startActivityForResult
。
答案 1 :(得分:0)
更改
this.startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
到
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
答案 2 :(得分:0)
将以下代码块添加到父onActivityResult
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
//send result to all child fragment
if(fragment!=this)
fragment.onActivityResult(requestCode, resultCode, data);
}
答案 3 :(得分:0)
与Intent一起使用的上下文可能指向其他内容。在您的片段中尝试
private Fragment fragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragment = this;
}
然后在您的片段上再次显示
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
fragment.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
RC_PHOTO_PICKER);
答案 4 :(得分:0)
不太确定,但是可能是片段正在调用该意图吗?您可以在单击imageView或按钮时尝试使用侦听器,然后拦截它并从父级活动中调用意图吗?