2021年Android引入SegmentedButton依赖报错及替代方案咨询
现有集成问题修复方案
- 处理仓库配置报错
你使用的是Gradle 7.0+版本,该版本默认开启了仓库优先级配置,不允许在模块级/项目级build.gradle中添加第三方仓库,需要修改根目录下的settings.gradle文件,在dependencyResolutionManagement的repositories块中添加JitPack仓库:
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { google() mavenCentral() // 新增JitPack仓库配置 maven { url 'https://jitpack.io' } } }
修改完成后删除模块级build.gradle中注释掉的allprojects相关仓库配置代码。
- 处理依赖找不到与compile废弃问题
清理模块级build.gradle的dependencies块中重复的两次SegmentedButton依赖声明,仅保留一行implementation声明即可,替换原有compile写法的同时避免重复依赖冲突:
dependencies { // 保留这一行即可,删除另外一行同库的依赖声明 implementation 'com.github.ceryle:SegmentedButton:v2.0.2' // 其余原有依赖保持不变 }
完成上述修改后重新同步Gradle,三个问题即可全部解决。
更推荐的替代组件方案
你项目中已经引入了1.4.0版本的Material Components官方库,原生自带的MaterialButtonToggleGroup组件可以完全实现分段按钮需求,无需引入已停止维护的第三方库,稳定性和适配性更强,基础使用示例如下:
<!-- 布局文件中的分段按钮实现 --> <com.google.android.material.button.MaterialButtonToggleGroup android:id="@+id/segmentedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" app:singleSelection="true" app:checkedButton="@id/btnFirst"> <com.google.android.material.button.MaterialButton android:id="@+id/btnFirst" style="?attr/materialButtonOutlinedStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项1"/> <com.google.android.material.button.MaterialButton android:id="@+id/btnSecond" style="?attr/materialButtonOutlinedStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项2"/> </com.google.android.material.button.MaterialButtonToggleGroup>
该组件支持单选、多选、自定义样式、选中状态监听等全部常用功能,完全可以替代第三方SegmentedButton组件。
内容的提问来源于stack exchange,提问作者Abdullah Omer
相关产品推荐
相关产品推荐

