当相机活动返回时,承载这个片段的活动有它的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);
}
}
我只是做了一个变通方法:
public static Fragment _tempFragment = null;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(_tempFragment != null)
_tempFragment.onActivityResult(requestCode, resultCode, data);
}
在Fragment中,在startActivityResult之前,设置
MainActivity._tempFragment = this;
在片段中的onActivityResult <——之后
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Do your job
{
}
MainActivity._tempFragment = null;
}
添加这个
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
当你将替换你的代码与上述代码,然后自动你的这个
public void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data){}
方法将开始工作
//No Need to write this code in onclick method
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent,1);
Toast.makeText(getContext(), "image"+intent, Toast.LENGTH_SHORT).show();
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)
}
}