来自Fragment中的适配器的startActivityForResult

时间:2017-05-22 19:41:57

标签: java android android-fragments android-camera

我有一个片段,我在其中填充了一个RecyclerView,一个帖子包含一个摄像头,我需要拍摄它拍照时带来的信息。我不知道怎么做。

请帮忙。

这是mi代码:

PostAdapter.java

        public HeaderViewHolder (View itemView) {
        super (itemView);
        this.mCamera = (ImageView) itemView.findViewById(R.id.ivCamera);
        mCameraPhoto = new CameraPhoto(itemView.getContext());
        this.mCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    ((Activity) v.getContext()).startActivityForResult(mCameraPhoto.takePhotoIntent(), CAMERA_REQUEST_ASIST);
                }catch (Exception e){
                    Log.e("Error camera permission", e.getMessage());
                }
            }
        });
    }

MainActivity.java

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String photoPath = mCameraPhoto.getPhotoPath();
    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);

        Log.d("Result in fragment",":D --> "+photoPath);
    }

}

MyFragment.java

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("Result in fragment",":D");
}

3 个答案:

答案 0 :(得分:3)

将片段传递给PostAdapter的构造函数。

class PostAdapter {
   private Fragment fragment;

   public PostAdapter(Fragment fragment) {
      this.fragment = fragment;
   }
}

然后在onclick

里面
this.mCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
                fragment.startActivityForResult(mCameraPhoto.takePhotoIntent(), CAMERA_REQUEST_ASIST);
            }catch (Exception e){
                Log.e("Error camera permission", e.getMessage());
            }
        }
    });

答案 1 :(得分:0)

使用getFragmentById()或getFragmentByTag()方法之一来获取对片段的引用

答案 2 :(得分:0)

您可以获取您拍摄的照片信息,如下所示。

在您的片段中

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            if(requestCode == CAMERA_REQUEST_ASIST ){
                String photoPath = mCameraPhoto.getPhotoPath();
                try {
                    // Update data in your Custom RecyclerView Adapter 
                    // and call notifyDatasetChanged

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }//end if resultCode
    }

更多信息https://github.com/kosalgeek/PhotoUtil/blob/master/README.md