为什么我没有收到onActivityResult的任何结果

时间:2016-06-11 15:33:42

标签: java android android-fragments onactivityresult

我在按下按钮时调用 showPickImageDialog()方法,从 AddFragment 启动 DialogFragment 。在 AlertDialogFragment onActivityResult 中,我将结果发送回 AddFragment ,但 AddFragment 未收到任何结果。有什么想法吗?

AddFragment:

class Utilisateur extends CI_Controller {

    public function inscription(){
        $data = array('header' => 'HeaderAccueil.php', 'body' => 'utilisateur/AjoutUtilForm.php');
        $this->load->view('StructureHtml.php', $data);
    }

在AlertDialogFragment中我从onActivityResult方法调用sendResult方法。调用SendResult方法我用Logs

检查了它

AlertDialogFragment:

    public class AddFragment extends Fragment {

    private static final int REQUEST_IMAGE = 3;
    private static final String DIALOG_IMAGE = "image";
    private static final String TAG = "TAG";

    void showPickImageDialog() {
        FragmentManager fm = getActivity()
                .getSupportFragmentManager();
        AlertDialogFragment pdialog = new AlertDialogFragment();
        pdialog.setTargetFragment(this, REQUEST_IMAGE);
        pdialog.show(fm, DIALOG_IMAGE);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


            if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){

                Log.e(TAG,"back in AddFragment");

            }
        }
}

1 个答案:

答案 0 :(得分:1)

您可以覆盖onActivityResult中的Activity方法并手动调用片段onActivityResult,如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
    fragment.onActivityResult(requestCode, resultCode, data);
}

您可以在Activity的onActivityResult方法中定义此部分:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){

    uri = data.getData();

        final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
        Cursor c = getActivity().getContentResolver()
                .query(uri,filePathColumn,null,null,null);

        if (c.moveToFirst()){
            int ids = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            uri = Uri.parse(c.getString(ids));
            filename = uri.toString();
            c.close();
        }
        // You do not need this any more
        //sendResult(Activity.RESULT_OK);
        //dismiss();
        // Just find your fragment and call it's onActivityResult
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
        fragment.onActivityResult(requestCode, resultCode, data);
    }

}

我认为这一改变可以帮助你。