当相机活动返回时,承载这个片段的活动有它的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);
}
}
我也面临着同样的问题,一旦我把这段代码从一个片段转移到一个实用工具类,将parentActivity作为参数传递,
Intent intent = new Intent(parentActivity, CameraCaptureActivity.class);
parentActivity.startActivityForResult(intent,requestCode);
然后我没有得到任何值在onActivityResult方法的片段,
之后,我把参数改为Fragment,所以修改后的method定义是这样的,
Intent intent = new Intent(fragment.getContext(), CameraCaptureActivity.class);
fragment.startActivityForResult(intent,requestCode);
在那之后,我能够在片段上的onActivityResult中获得值
如果在fragment类内部的onActivityResult方法有问题,并且你想要更新一些也在fragment类内部的东西,使用:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK)
{
// If the user had agreed to enabling Bluetooth,
// populate the ListView with all the paired devices.
this.arrayDevice = new ArrayAdapter<String>(this.getContext(), R.layout.device_item);
for(BluetoothDevice bd : this.btService.btAdapater.getBondedDevices())
{
this.arrayDevice.add(bd.getAddress());
this.btDeviceList.setAdapter(this.arrayDevice);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
只要加上这个。变量,如上面代码所示。否则,该方法将在父活动中被调用,并且该变量不会在当前实例中更新。
我还通过将这段代码放到MainActivity中进行测试,用HomeFragment类替换它,并将变量设置为静态。我得到了我所期望的结果。
因此,如果你想让片段类拥有自己的onActivityResult实现,上面的代码示例就是答案。
我在使用ChildFragmentManager时有同样的问题。管理器不会将结果传递给嵌套片段,您必须在基本片段中手动执行此操作。
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag(childTag);
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, intent);
}
}
对于嵌套片段(例如,当使用ViewPager时)
在你的主要活动:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
在你的主顶级片段(ViewPager片段)中:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
YourFragment frag = (YourFragment) getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());
frag.yourMethod(data); // Method for callback in YourFragment
super.onActivityResult(requestCode, resultCode, data);
}
在YourFragment(嵌套片段)中:
public void yourMethod(Intent data){
// Do whatever you want with your data
}