为什么安卓的Facebook界面不能与Fragments一起使用?[英] Why doesn't Android Facebook interface work with Fragments?

本文是小编为大家收集整理的关于为什么安卓的Facebook界面不能与Fragments一起使用?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在将一些Android Facebook 代码从Activity切换到Fragment.在开关之前,一切都很好,但是现在onComplete()回调尚未执行.

Facebook代码是否不使用 fragments ,还是我做错了什么?

这是原始代码(在SherlockActivity中):

if (!mFacebook.isSessionValid()) {
    mFacebook.authorize(MyActivity.this, permissions, new DialogListener() {
        @Override
        public void onComplete(Bundle values) { ... }    // CALLED AS EXPECTED
    }
}

这是新代码(在sherlockfragment中):

if (!mFacebook.isSessionValid()) {
    mFacebook.authorize(getActivity(), permissions, new DialogListener() {
        @Override
        public void onComplete(Bundle values) { ... }    // DOES NOT GET CALLED
    }
}

活动和片段都按照Facebook的要求包括相同的onActivityResult():

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

感谢您的帮助!

编辑:提出类似的问题 here ,接受的答案是将Fragment更改为FragmentActivity.但是我看不出这是如何有帮助的,因为那是不再是Fragment(出于其他原因我需要).建议?

编辑2:我滚动了自己的解决方案.请参阅下面.

推荐答案

据我所知,Facebook auth API不支持 fragments .具体来说,Facebook authorize()的onComplete()回调可与活动一起使用,但与 fragments .

.

因此,我为片段进行了简单的解决方法.该解决方案取决于以下事实:onActivityResult()在authorize()呼叫完成时,在父活动中都调用了以下事实,因此您可以使用它来设置单独的 challback 片段的机制.

首先,在父活动中设置一个变量携带目标片段名称,例如

TargetFragment mTargetFragment;

首先实例化片段时,您可以将其初始化:

@Override
public void onAttachFragment(Fragment fragment) {
    super.onAttachFragment(fragment);

    String fragmentSimpleName = fragment.getClass().getSimpleName();

    if (fragmentSimpleName.equals("TargetFragment"))
        mTargetFragment = (TargetFragment)fragment;        
}

然后在OnActivityResult()函数中添加几行:

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

    if (mTargetFragment != null)       
        mTargetFragment.myCallBack(requestCode, resultCode, data);
}

现在,您只需模仿您通常会在新的myCallback()函数中放入oncomplete()回调的代码:

public void myCallBack(int requestCode, int resultCode, Intent data) {
    mFacebook.authorizeCallback(requestCode, resultCode, data);

    // other code from your onComplete() function ...
}

我希望这可以帮助别人.欢呼!

其他推荐答案

下载了最新版本的Facebook SDK,并且我有同样的问题,即 gcl1"> gcl1 正常工作,但我必须在活动结果上做更多的事情,所以我已经在父活动上做了这一点:

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

其他推荐答案

Facebook SDK不适合片段,而是碎片性. 所以你需要:

  1. 在您的父片段中捕获onactivityResult()中的fb登录信息.
  2. 将活动结果传递给您的孩子碎片

示例:

1.

public class MainActivity extends FragmentActivity(){


/* catch FACEBOOK login info and call onFBLoginActivityResult() to pass it to FacebookFrragment*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

       android.support.v4.app.FragmentManager fm =   getSupportFragmentManager();
       FacebookFragment fbfragment= (FacebookFragment ) fm.findFragmentByTag("facebookfragment");
       selectPKEConfigFragment.onFBLoginActivityResult(requestCode, resultCode, data);

    }

}

2.

public class FacebookFragment extends Fragment{

        @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                Bundle savedInstanceState) {
        // ........... 

         // start Facebook Login

                    Session.openActiveSession(getActivity(), true, new Session.StatusCallback() {

                      // callback when session changes state
                      @Override
                      public void call(Session session, SessionState state, Exception exception) {
                        if (session.isOpened()) {
                          // make request to the /me API
                          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                            // callback after Graph API response with user object
                            @Override
                            public void onCompleted(GraphUser user, Response response) {
                              if (user != null) {
                               // TextView welcome = (TextView) findViewById(R.id.welcome);
                               // welcome.setText("Hello " + user.getName() + "!");
                                  Log.i(TAG,"User: " + user.getName());
                              }
                              else  Log.i(TAG,"User: null");
                            }
                          });
                        }
                        else Log.i(TAG,"session closed");
                      }


                    });

            }

        /*
         * replace onActivityResult
         */
        public void onFBLoginActivityResult(int requestCode, int resultCode, Intent data){
             Log.i(TAG,"Activity result SelectPKEConfig");
            Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
        }

本文地址:https://www.itbaoku.cn/post/102331.html

问题描述

I'm switching some Android Facebook code from an Activity to a Fragment. Prior to the switch everything worked fine, but now the onComplete() callback is not being executed.

Does the Facebook code not work with Fragments, or am I doing something wrong?

Here's the original code (in a SherlockActivity):

if (!mFacebook.isSessionValid()) {
    mFacebook.authorize(MyActivity.this, permissions, new DialogListener() {
        @Override
        public void onComplete(Bundle values) { ... }    // CALLED AS EXPECTED
    }
}

And here's the new code (in a SherlockFragment):

if (!mFacebook.isSessionValid()) {
    mFacebook.authorize(getActivity(), permissions, new DialogListener() {
        @Override
        public void onComplete(Bundle values) { ... }    // DOES NOT GET CALLED
    }
}

Both the Activity and the Fragment include the same onActivityResult() as required by Facebook:

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

Thanks for your help!

EDIT: A similar question is asked here, where the accepted answer is to change the Fragment to a FragmentActivity. But I don't see how this helps, as then it's no longer a Fragment (which I need for other reasons). Suggestions?

EDIT 2: I rolled my own solution. See below.

推荐答案

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!

其他推荐答案

I have downloaded the latest version of Facebook SDK and I have the same problem, the solution of gcl1 works fine but I have to do more things on activity result so I have made this on the parent activity:

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

其他推荐答案

Facebook SDK don't works with Fragment, but works with FragmentActivity. So you need:

  1. Catch the FB login info in onActivityResult() in your parent FragmentActivity.
  2. Pass activity results to your child Fragment

example:

1.

public class MainActivity extends FragmentActivity(){


/* catch FACEBOOK login info and call onFBLoginActivityResult() to pass it to FacebookFrragment*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

       android.support.v4.app.FragmentManager fm =   getSupportFragmentManager();
       FacebookFragment fbfragment= (FacebookFragment ) fm.findFragmentByTag("facebookfragment");
       selectPKEConfigFragment.onFBLoginActivityResult(requestCode, resultCode, data);

    }

}

2.

public class FacebookFragment extends Fragment{

        @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                Bundle savedInstanceState) {
        // ........... 

         // start Facebook Login

                    Session.openActiveSession(getActivity(), true, new Session.StatusCallback() {

                      // callback when session changes state
                      @Override
                      public void call(Session session, SessionState state, Exception exception) {
                        if (session.isOpened()) {
                          // make request to the /me API
                          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                            // callback after Graph API response with user object
                            @Override
                            public void onCompleted(GraphUser user, Response response) {
                              if (user != null) {
                               // TextView welcome = (TextView) findViewById(R.id.welcome);
                               // welcome.setText("Hello " + user.getName() + "!");
                                  Log.i(TAG,"User: " + user.getName());
                              }
                              else  Log.i(TAG,"User: null");
                            }
                          });
                        }
                        else Log.i(TAG,"session closed");
                      }


                    });

            }

        /*
         * replace onActivityResult
         */
        public void onFBLoginActivityResult(int requestCode, int resultCode, Intent data){
             Log.i(TAG,"Activity result SelectPKEConfig");
            Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
        }