当相机活动返回时,承载这个片段的活动有它的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);
}
}
解决方案1:
调用startActivityForResult(intent, REQUEST_CODE);而不是getActivity()。startActivityForResult(意图,REQUEST_CODE);。
解决方案2:
当startActivityForResult(intent, REQUEST_CODE);调用活动的onActivityResult(requestCode,resultcode,intent),然后你可以从这里调用片段onActivityResult(),传递requestCode,resultcode和intent。
You can simply override BaseActivity onActivityResult on fragment baseActivity.startActivityForResult .
On BaseActivity add interface and override onActivityResult.
private OnBaseActivityResult baseActivityResult;
public static final int BASE_RESULT_RCODE = 111;
public interface OnBaseActivityResult{
void onBaseActivityResult(int requestCode, int resultCode, Intent data);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(getBaseActivityResult() !=null && requestCode == BASE_RESULT_RCODE){
getBaseActivityResult().onBaseActivityResult(requestCode, resultCode, data);
setBaseActivityResult(null);
}
On Fragment implements OnBaseActivityResult
@Override
public void onBaseActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("RQ","OnBaseActivityResult");
if (data != null) {
Log.d("RQ","OnBaseActivityResult + Data");
Bundle arguments = data.getExtras();
}
}
这个变通方法会奏效。
在你的片段中,调用
this.startActivityForResult(intent, REQUEST_CODE);
这里this指的是片段。否则就照@Clevester说的做:
Fragment fragment = this;
....
fragment.startActivityForResult(intent, REQUEST_CODE);
我还得打电话
super.onActivityResult(requestCode, resultCode, data);
在父活动的onActivityResult中使其工作。
(我改编自@Clevester的回答。)