当相机活动返回时,承载这个片段的活动有它的onActivityResult被调用。
我的片段开始一个活动的结果与意图发送给相机拍照。图片应用程序加载正常,拍摄照片并返回。然而onActivityResult从未被击中。我设置了断点,但什么都没有触发。一个片段可以有onActivityResult吗?我想是的,因为它是一个已提供的函数。为什么这个没有被触发?
ImageView myImage = (ImageView)inflatedView.findViewById(R.id.image);
myImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == 1888 ) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
((ImageView)inflatedView.findViewById(R.id.image)).setImageBitmap(photo);
}
}
首先你需要在Activity中重写这段代码;
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
之后,在你的片段中,
startActivityForResult(intent,GALLERY_REQUEST_CODE);
在你的片段中,
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result code is RESULT_OK only if the user selects an Image
if (resultCode == Activity.RESULT_OK) {
}
}
对于那些使用Android导航组件的人来说,Kotlin版本的灵感来自Mohit Mehta的答案
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
supportFragmentManager.primaryNavigationFragment?.childFragmentManager?.fragments?.forEach { fragment ->
fragment.onActivityResult(requestCode, resultCode, data)
}
}
从@Mohit Mehta获得帮助,如果你正在使用导航组件,这可能会帮助你。这对我很有效。
在MainActivity的onActivityResult方法中粘贴以下代码:
for (Fragment fragment : navHostFragment.getChildFragmentManager().getFragments()){
if (fragment != null){
Log.d(TAG, "onResult Has Been Sent!");
fragment.onActivityResult(requestCode, resultCode, data);
}
}
在YOUR FRAGMENT的onActivityResult方法中,你可以得到结果。
希望这对你有所帮助。
Kotlin版本(在你的活动onActivityResult()中)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//add following lines in your activity
if(supportFragmentManager?.fragments!=null && supportFragmentManager?.fragments!!.size>0)
for (i in 0..supportFragmentManager?.fragments!!.size-1) {
val fragment= supportFragmentManager?.fragments!!.get(i)
fragment.onActivityResult(requestCode, resultCode, data)
}
}