我尝试使用自定义界面登录Facebook,它在Activity类中运行良好。我也必须在Fragment做同样的事情。但回调没有执行。是不是可以在Fragment的OnActivityResult中添加CallbackResult?
答案 0 :(得分:24)
您只需在Activity onActivityResult中添加此代码。
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
//System.out.println("@#@");
fragment.onActivityResult(requestCode, resultCode, data);
}
然后你的片段onActivityResult肯定会起作用。
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
答案 1 :(得分:21)
是的,可以在片段中实现facebook登录,您唯一需要做的就是在您的主机活动中调用OnActivityResult,如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment = getFragmentManager().findFragmentById(R.id.your_host_fragment_in_activity);
fragment.onActivityResult(requestCode, resultCode, data);
}
然后在你的片段中再次调用onActivityResult。
答案 2 :(得分:2)
您只需要在片段内添加一行
fbLoginButton.setFragment(this);
您将在
中获得控件@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {}
答案 3 :(得分:0)
这是我的代码片段:
class LoginFragment : Fragment() {
private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
private lateinit var callBackManager: CallbackManager
private val TAG = "LoginFragment"
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentLoginBinding.inflate(inflater, container, false)
callBackManager = CallbackManager.Factory.create()
binding.loginButton.setPermissions(listOf("email, public_profile"))
binding.loginButton.setFragment(this)
binding.loginButton.registerCallback(callBackManager,
object : FacebookCallback<LoginResult?> {
override fun onSuccess(loginResult: LoginResult?) {
Log.d(TAG, "onSuccess: ${loginResult?.accessToken?.userId}")
}
override fun onCancel() {
// App code
}
override fun onError(exception: FacebookException) {
Log.d(TAG, "onError: $exception")
}
})
return binding.root
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
callBackManager.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}