Android端Google登录问题:RC_SIGN_IN、updateUI无法解析且登录按钮失效
解决Google登录Android开发中的三个核心问题
让我们一步步搞定你遇到的这几个问题:
1. RC_SIGN_IN 无法解析的问题
RC_SIGN_IN 是需要你自己定义的请求码常量,官方文档只是用这个名称做示例,并不会自动生成。你只需要在MainActivity类里添加一行静态常量声明就行:
public class MainActivity extends AppCompatActivity { // 自定义请求码,值只要是唯一的int类型就可以 private static final int RC_SIGN_IN = 1001; // 你的其他代码... }
2. updateUI() 无法解析的问题
updateUI() 是官方文档示意的自定义方法,用来根据登录状态更新界面(比如切换登录按钮和用户信息的显示),你得自己实现这个方法。给你一个简单的参考实现:
private void updateUI(GoogleSignInAccount account) { if (account != null) { // 用户已登录:隐藏登录按钮,展示用户信息 mSignInButton.setVisibility(View.GONE); TextView resultTv = findViewById(R.id.text_view_result); resultTv.setText("欢迎回来," + account.getDisplayName()); } else { // 用户未登录:显示登录按钮 mSignInButton.setVisibility(View.VISIBLE); TextView resultTv = findViewById(R.id.text_view_result); resultTv.setText("请完成登录"); } }
把这个方法加到MainActivity里,位置放在handleSignInResult方法下面或者其他合适的地方就行。
3. 登录按钮无法工作的问题
看你的布局XML,问题出在布局层级遮挡:SignInButton和NestedScrollView都直接放在FrameLayout里,而NestedScrollView的宽高是match_parent,它完全盖在了登录按钮上面,导致你点击不到按钮。
调整布局结构就能解决,把登录按钮移到NestedScrollView内部就不会被遮挡了:
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 把SignInButton移到NestedScrollView内部 --> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp"/> <TextView android:id="@+id/text_view_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000" android:layout_marginTop="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.v4.widget.NestedScrollView> </FrameLayout>
另外提一句:你给TextView加了ConstraintLayout的约束属性,但父布局是NestedScrollView(属于FrameLayout体系),这些约束其实不会生效。如果想让TextView居中,可以把NestedScrollView的子控件换成LinearLayout并设置gravity,或者直接把FrameLayout换成ConstraintLayout,不过先搞定按钮点击问题优先。
把这三个问题都修复后,你的Google登录流程应该就能正常跑起来了。
内容的提问来源于stack exchange,提问作者user11016692
相关产品推荐
相关产品推荐

