实际上,如果您查看Android 版 Facebook Docs,您会看到登录示例在其中使用了片段。
Facebook SDK 提供了LoginButton小部件,它有一个名为 setFragment 的方法,您可以传递要使用登录功能的目标片段。
在您的片段布局中
添加 Facebook SDK 提供的登录按钮。
<com.facebook.widget.LoginButton
android:id="@+id/facebook_login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp" />
在你的片段中
在您的片段中创建UiLifecycleHelper和StatusCallback对象。
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
添加处理用户状态更改的方法。
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i("LoginFragment", "Logged in...");
Log.i("LoginFragment", session.getAccessToken());
doAnythingWithTheFacebookToken(session.getAccessToken());
} else if (state.isClosed()) {
// this part is called when user login fails
Log.i("LoginFragment", "Logged out...");
}
}
覆盖片段生命周期方法
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate your fragment view
facebookLoginButton = (LoginButton) view.findViewById(R.id.facebook_login_button);
facebookLoginButton.setFragment(this);
}
@Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
结果
通常你需要在你的活动中覆盖onActivityResult但在 Facebook 登录按钮上调用setFragment()允许你的片段在它自己的onActivityResult中接收结果。
如果您想使用不同的按钮(例如您自己的按钮):
而已。