如何将视图设置为片段侦听器

时间:2016-02-25 18:52:20

标签: android android-fragments listener onactivityresult

从视图中我称之为片段,以便我可以拍照。我将视图设置为侦听器

AuxPhotoFragment auxFragment = AuxPhotoFragment.newInstance(photoFile);
auxFragment.setOnPhotoTakenListener(this);

onActivityResult侦听器被发现为null。任何想法如何在侦听器不是Context时将侦听器传递给片段?有关背景信息,请参阅https://stackoverflow.com/questions/35617124/startactivityforresult-inside-view-crash-on-rotation

我使用的片段看起来像这样

public class AuxPhotoFragment extends Fragment {
    private static final String ARG_PHOTO_FILE = "paramPhotoFile";

    private File photoFile;

    private OnPhotoTakenListener mListener;

    public AuxPhotoFragment() {
        // Required empty public constructor
    }

    public static AuxPhotoFragment newInstance(File file) {
        AuxPhotoFragment fragment = new AuxPhotoFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PHOTO_FILE, file);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            photoFile = (File) getArguments().getSerializable(ARG_PHOTO_FILE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return null;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);
    }

    public void setOnPhotoTakenListener(OnPhotoTakenListener onPhotoTakenListener) {
        mListener = onPhotoTakenListener;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Activity.RESULT_OK == resultCode && Constants.REQUEST_CODE_SINGLE_PHOTO == requestCode) {
            mListener.addPhotoToViewAndContentProvider(getContext(), photoFile);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public interface OnPhotoTakenListener {
        void addPhotoToViewAndContentProvider(Context context, File photoFile);
    }
}

我用

来称呼它
AuxPhotoFragment auxFragment = AuxPhotoFragment.newInstance(photoFile);
                auxFragment.setOnPhotoTakenListener(this);
                fragmentManager.beginTransaction().add(auxFragment, TAG).commit();
                fragmentManager.executePendingTransactions();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                auxFragment.startActivityForResult(takePictureIntent, REQUEST_CODE_PHOTO);

注意:正如原始问题一样,我在旋转时遇到空问题:即我进入相机,旋转,拍照,然后点击确定接受图片。

0 个答案:

没有答案