Calling Google Play Game Services from a fragment

后端 未结 4 1609
悲哀的现实
悲哀的现实 2020-12-11 09:19

I have implemented some Google Play Game Services features in my Android app as a separate Activity and I am now trying to rewrite my code as an (Action Bar Sherlock) fragme

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 09:41

    You can forward the onActivityResult call to the fragment like this:

    We should bitwise shift a request code by 16 bits.

    public static final int REQUEST_CHECK_SETTINGS = 1<<16; //shifted 1 16 bits
    

    Add this to the activity who owns the fragment.

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

    Note: I've figured this out from the source code of onActivityResult in FragmentActivity. It is shifting the requestCode 16 bits to the right.

    /**
     * Dispatch incoming result to the correct fragment.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mFragments.noteStateNotSaved();
        int index = requestCode>>16;
        if (index != 0) {
            index--;
            final int activeFragmentsCount = mFragments.getActiveFragmentsCount();
            if (activeFragmentsCount == 0 || index < 0 || index >= activeFragmentsCount) {
                Log.w(TAG, "Activity result fragment index out of range: 0x"
                        + Integer.toHexString(requestCode));
                return;
            }
            final List activeFragments =
                    mFragments.getActiveFragments(new ArrayList(activeFragmentsCount));
            Fragment frag = activeFragments.get(index);
            if (frag == null) {
                Log.w(TAG, "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            } else {
                frag.onActivityResult(requestCode&0xffff, resultCode, data);
            }
            return;
        }
    
        super.onActivityResult(requestCode, resultCode, data);
    }
    

    Note 2: I would be glad if someone could tell me why using this method would be a bad approach

提交回复
热议问题