如何在Android中使用按钮实现虚线样式的Tab选中效果

侧边Tab选中效果Drawable实现方案
完全可以通过drawable资源实现该效果,无需自定义控件,具体实现步骤如下:
1. 创建各状态的shape背景
选中状态背景(bg_tab_selected.xml)
如果需要带左侧蓝色指示条,可使用layer-list实现:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 左侧蓝色选中指示条 --> <item> <shape android:shape="rectangle"> <solid android:color="#2196F3" /> </shape> </item> <!-- 选中态背景色,左侧留4dp露出指示条 --> <item android:left="4dp"> <shape android:shape="rectangle"> <solid android:color="#E8F0FE" /> </shape> </item> </layer-list>
如果不需要指示条,直接使用纯色矩形shape即可:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#E8F0FE" /> </shape>
默认状态背景(bg_tab_normal.xml)
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/transparent" /> </shape>
2. 创建状态选择器(selector_tab_bg.xml)
将不同状态对应背景配置到选择器中:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中状态 --> <item android:state_selected="true" android:drawable="@drawable/bg_tab_selected" /> <!-- 按下状态,可根据需求调整是否和选中态保持一致 --> <item android:state_pressed="true" android:drawable="@drawable/bg_tab_selected" /> <!-- 默认状态 --> <item android:drawable="@drawable/bg_tab_normal" /> </selector>
3. 绑定到按钮并实现切换逻辑
- 在布局文件中,将侧边Tab按钮的
android:background属性设置为@drawable/selector_tab_bg - 代码中处理Tab点击事件:每次点击某一个Tab时,先将所有Tab的
setSelected(false),再将当前点击的Tab调用setSelected(true)即可自动切换背景样式。
内容的提问来源于stack exchange,提问作者Kundan Jha
相关产品推荐
相关产品推荐

