Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View calling startActivityForResult

I created custom compound view where I incorporate functionality to take pictures.

I'm calling it like this (from view):

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity)mContext).startActivityForResult(intent, index);

This part works good. What I don't know how to do is how do I implement onActivityResult inside my custom view?

Or should I catch this inside Activity and than re-route into my view? Doesn't look like very nice solution..

like image 691
katit Avatar asked Jul 05 '11 17:07

katit


1 Answers

Here's a static function to implementing @riwnodennyk's solution, while overcoming the Fragment must be static and not in anonymous class error:

public static void myStartActivityForResult(FragmentActivity act, Intent in, int requestCode, OnActivityResult cb) {
    Fragment aux = new FragmentForResult(cb);
    FragmentManager fm = act.getSupportFragmentManager();
    fm.beginTransaction().add(aux, "FRAGMENT_TAG").commit();
    fm.executePendingTransactions();
    aux.startActivityForResult(in, requestCode);
}

public interface OnActivityResult {
    void onActivityResult(int requestCode, int resultCode, Intent data);
}

@SuppressLint("ValidFragment")
public static class FragmentForResult extends Fragment {
    private OnActivityResult cb;
    public FragmentForResult(OnActivityResult cb) {
        this.cb = cb;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (cb != null)
            cb.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
    }
}

Usage example:

    Intent inPhonebook = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    myStartActivityForResult((FragmentActivity) getContext(),
            inPhonebook, REQUEST_CODE_PICK_CONTACT, this::onContacts);
like image 76
jazzgil Avatar answered Sep 19 '22 06:09

jazzgil