Android Studio中自定义Google登录按钮集成报错问题
自定义Google登录按钮集成方案
我看到你正在尝试用第三方自定义Google登录按钮库集成登录功能,我帮你把依赖配置整理成规范格式,同时补充关键的集成步骤,方便你快速上手:
1. 规范依赖配置
首先,注意Android Studio 3.0及以上版本推荐使用implementation替代compile,调整后的完整依赖配置如下:
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' implementation 'com.android.support:design:26.1.0' // 替换compile为implementation,符合当前Android构建规范 implementation 'com.shobhitpuri.custombuttons:google-signin:1.0.0' testImplementation 'junit:junit:4.12' // 补全常见测试依赖示例 }
2. 布局中添加自定义登录按钮
在XML布局文件里添加这个自定义按钮,还可以通过属性自定义外观:
<com.shobhitpuri.custombuttons.GoogleSignInButton android:id="@+id/google_sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" app:buttonColor="@color/white" app:textColor="@color/black" app:buttonText="Sign in with Google" />
3. 代码中实现登录逻辑
在Activity或Fragment里初始化按钮,并绑定Google登录的核心逻辑:
// 定义登录请求码 private static final int RC_SIGN_IN = 1001; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); GoogleSignInButton signInButton = findViewById(R.id.google_sign_in_button); signInButton.setOnClickListener(v -> startGoogleSignIn()); } private void startGoogleSignIn() { // 配置Google登录选项,按需请求用户信息 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestProfile() .build(); // 创建Google登录客户端 GoogleSignInClient signInClient = GoogleSignIn.getClient(this, gso); // 启动登录Intent Intent signInIntent = signInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); }
4. 处理登录结果
重写onActivityResult方法(适配旧版Android API)来处理登录回调:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { // 解析登录结果 Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { GoogleSignInAccount account = task.getResult(ApiException.class); // 登录成功,获取用户信息 String userEmail = account.getEmail(); String userName = account.getDisplayName(); Uri userPhoto = account.getPhotoUrl(); // 这里添加你的业务逻辑,比如跳转到主页面、保存用户信息等 } catch (ApiException e) { // 登录失败,打印错误信息 Log.e("GoogleSignIn", "登录失败,错误码:" + e.getStatusCode()); } } }
内容的提问来源于stack exchange,提问作者sai
相关产品推荐
相关产品推荐

