onActivityResult 未在片段 android 中调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20062840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:15:44  来源:igfitidea点击:

onActivityResult not called in fragment android

androidfragment

提问by user1920582

This is my code to take picture from gallery.

这是我从画廊拍照的代码。

public class FragmentLayout1 extends Fragment implements OnClickListener {

    View root;
    Context c;
    Button add_image;
    DialogAddImage image;
    RelativeLayout layout_image;
    String path;
    RunAnimations anima;


    public void setContext(Context c){
        this.c = c;
        Constants con = new Constants(c);   
    }

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        anima = new RunAnimations();
        image = new DialogAddImage((Activity) c);

        Bundle bun = new Bundle();
        path = bun.getString("path");

        root = inflater.inflate(R.layout.layout_1, container, false);
        add_image = (Button)root.findViewById(R.id.button2);
        add_image.setOnClickListener(this);

        layout_image = (RelativeLayout)root.findViewById(R.id.layout_image);

        if(!TextUtils.isEmpty(path)){
            Log.e("path", path);
             Drawable d = Drawable.createFromPath(path);
             layout_image.setBackground(d);
        }


        return root;


    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        anima.loadAnimationView(c, R.anim.alpha_button, v);
        if(v == add_image){
            image.showDialog();
        }

    }


     //============= fungsi untuk menerima hasil pilihan user dalam kotak dialog ambil gambar=============
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("result", "Result");
        new ImageResult((Activity) c).resultOfImage(requestCode, resultCode, data, image.getUri(), false);
    }

in method on click , I've button add_image. add_image will show a dialog for user to take picture from camera or gallery And this is my dialog code

在 click 方法中,我有按钮 add_image。add_image 将显示一个对话框供用户从相机或画廊拍照 这是我的对话框代码

public class DialogAddImage{
    private Activity c;
    private Uri mImageCaptureUri;
    private Dialog dialog;
    AnimasiActivity aa;
    Button camera, galeri;

    public DialogAddImage(Activity c){
        this.c = c;

        aa = new AnimasiActivity(c);
        setDialog();
    }

    //untuk mendapatkan uri yang menyimpan informasi path file image
    public Uri getUri(){
        return mImageCaptureUri;
    }


    @SuppressWarnings("deprecation")
    private void setDialog(){       
        dialog = new Dialog(c);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);   
        dialog.setContentView(R.layout.dialog_add_image);           
        dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

        camera = (Button) dialog.findViewById(R.id.button1);
        galeri = (Button)dialog.findViewById(R.id.button2);

        //kalo user pilih dari kamera
        camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {           
                hideDialog();
                Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String file_name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
                File file = new File(Constants.path_image +file_name + ".jpg");
                mImageCaptureUri = Uri.fromFile(file);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                try {                        
                    intent.putExtra("return-data", true);
                    intent.putExtra("mImageCaptureUri", mImageCaptureUri);                            

                    aa.startForwardForResult(intent, Constants.PICK_FROM_CAMERA);
                } catch (Exception e) {
                    e.printStackTrace();   
                }  



            }
        });

        //kalo user pilih dari galery
        galeri.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {                
                hideDialog();
                Intent intent = new Intent(); 
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);                   

                aa.startForwardForResult(intent, Constants.PICK_FROM_FILE);
            }

        });



    }

    public void showDialog(){

        dialog.show();
    }

    public void hideDialog(){
        dialog.dismiss();
    }


}

But when I've choose image from gallery , this image not showing in my fragment. And method onActivityResult never called, but why??? any solution , please

但是当我从图库中选择图像时,此图像未显示在我的片段中。和方法 onActivityResult 从未调用过,但为什么???任何解决方案,请

回答by umesh

Make sure you call startActivityForResult() and not getActivity().startActivityForResult() from your fragment. refer onActivityResult is not being called in Fragment

确保从片段中调用 startActivityForResult() 而不是 getActivity().startActivityForResult() 。请参阅onActivityResult没有被称为片段

回答by SweetWisher ツ

Override onActivityResultin parent Activity i.e. parent of all fragment

onActivityResult在父 Activity 中覆盖,即所有片段的父

回答by waqaslam

If you are overriding onActivityResultin your Activitythen make sure you do call super.onActivityResultthere too in order to propagate the result to your fragments.

如果您要覆盖您的内容onActivityResult,请Activity确保您super.onActivityResult也在那里调用,以便将结果传播到您的片段。

回答by Rakshith Raj S

Issue is very sensitive and little tricky the observation(fix) i have made for this as follows,

问题非常敏感,而且我为此所做的观察(修复)有点棘手,如下所示,

When u called Activity B from Activity A the source activity(A) instance should be in stack(memory) to invoke "onActivityResult" callback.

当你从活动 A 调用活动 B 时,源活动(A)实例应该在堆栈(内存)中以调用“onActivityResult”回调。

The issue explained with reason below,

问题解释如下,

Observation: From Material design back and NavUtils.navigateUpFromSameTask - the description of navigateUpFromSameTask as follows "Convenience method that is equivalent to calling navigateUpTo(sourceActivity, getParentActivityIntent (sourceActivity)). sourceActivity will be finished by this call"

观察:从Material design回来和NavUtils.navigateUpFromSameTask——navigateUpFromSameTask的描述如下“相当于调用navigateUpTo(sourceActivity,getParentActivityIntent(sourceActivity))的便捷方法。sourceActivity会被这个调用完成”

remember sourceActivity (A) is removed from stack(memory) when used this method.

请记住,使用此方法时,sourceActivity (A) 从堆栈(内存)中删除。

when there is no sourceActivity(A) no base instance(A) left to invoke "onActivityResult" callback.

当没有 sourceActivity(A) 时,没有基础实例 (A) 可以调用“onActivityResult”回调。

回答by Khaled Lela

  1. You can simply override BaseActivity onActivityResulton fragment baseActivity.startActivityForResult.

  2. On BaseActivity add interface

    private OnBaseActivityResult baseActivityResult;

  3. On Fragment implements OnBaseActivityResult

  1. 您可以简单地onActivityResult在 fragment 上覆盖 BaseActivity baseActivity.startActivityForResult

  2. 在 BaseActivity 上添加接口

    private OnBaseActivityResult baseActivityResult;

  3. On Fragment 实现OnBaseActivityResult

Check my answer here

在这里检查我的答案

回答by Nabil Souk

I have a custom DialogFragment and I faced the same issue. No need to trigger it from the parent's method. You have to call startActivityForResult() and not getActivity().startActivityForResult() just like @umesh answered above.

我有一个自定义的 DialogFragment 并且我遇到了同样的问题。无需从父级的方法触发它。您必须调用 startActivityForResult() 而不是 getActivity().startActivityForResult() 就像上面@umesh 回答的那样。

回答by Abhilash Das

When you call startActivityForResultfrom a fragment, the result is sent back to your activity's onActivityResult. Instead use super.onactivityResultin your activity's onActivityResultand the result will instead be sent back to your fragment's onActivityResult. You can write your code here. Don't use getActivity.onactivityResultin your fragment's onActivityResultbecause it will refer to the activity's onActivityResult.

当您startActivityForResult从片段调用时,结果将发送回您的活动的onActivityResult. 而是super.onactivityResult在您的活动中使用,onActivityResult结果将被发送回您的片段的onActivityResult. 您可以在此处编写代码。不要getActivity.onactivityResult在您的片段中使用,onActivityResult因为它会引用活动的onActivityResult.

回答by Jason Crosby

Also if you call startActivityForResult()from your fragment, then onActivityResult()will be called in your fragment. And if you call startActivityForResult()from your activity, then onActivityResult()will be called in your activity. Basically where you call startActivityForResult()is where onActivityResult()will be called.

此外,如果您startActivityForResult()从您的片段中调用,那么onActivityResult()将在您的片段中调用。如果您startActivityForResult()从您的活动中调用,那么onActivityResult()将在您的活动中调用。基本上你打电话startActivityForResult()的地方就是onActivityResult()会被调用的地方。

Another thing, in Android the prefered way to create dialogs is to extend the DialogFragmentclass.

另一件事,在 Android 中创建对话框的首选方法是扩展DialogFragment类。