Why doesn't Android Facebook interface work with Fragments?

前端 未结 5 518
粉色の甜心
粉色の甜心 2021-01-07 05:21

I\'m switching some Android Facebook code from an Activity to a Fragment. Prior to the switch everything worked fine, but now the

5条回答
  •  别那么骄傲
    2021-01-07 05:55

    As far as I could determine, the Facebook auth API does not support Fragments. Specifically, the onComplete() callback from the Facebook authorize() call works with Activities, but not with Fragments.

    So I put together a simple workaround for Fragments. The solution depends on the fact that onActivityResult() is also called in the parent Activity when the authorize() call completes, so you can use it to set up a separate callback mechanism for the Fragment.

    First, set up a variable in the parent Activity to carry the target Fragment's name, say

    TargetFragment mTargetFragment;
    

    You can initialize it when the Fragment is first instantiated like this:

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
    
        String fragmentSimpleName = fragment.getClass().getSimpleName();
    
        if (fragmentSimpleName.equals("TargetFragment"))
            mTargetFragment = (TargetFragment)fragment;        
    }
    

    Then add a couple of lines to the onActivityResult() function:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (mTargetFragment != null)       
            mTargetFragment.myCallBack(requestCode, resultCode, data);
    }
    

    Now you can just mimic the code you would ordinarily put in the onComplete() callback in the new myCallBack() function:

    public void myCallBack(int requestCode, int resultCode, Intent data) {
        mFacebook.authorizeCallback(requestCode, resultCode, data);
    
        // other code from your onComplete() function ...
    }
    

    I hope this can help someone else. Cheers!

提交回复
热议问题