做项目的时候有这样的需求,点击需要动态更换背景和字体颜色,所以自己就通过Selector实现了这个功能
步骤
- 新建更换背景的selector和对应shape
//注意这里 android:state_selected="true" 需要先设置。然后设置 false的状态
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_community_sign_in_selected" android:state_selected="true" />
<item android:drawable="@drawable/shape_community_sign_in_default" android:state_selected="false" />
</selector>
//android:state_selected="true"
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/qb_px_2"/>
<solid android:color="#F0F7FF" />
</shape>
// android:state_selected="false"
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/qb_px_2" />
<solid android:color="@color/color_1CA0F1" />
</shape>
- 新建更换字体颜色的Selector
//同样先设置 android:state_selected="true"的状态。然后设置false的状态
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/community_look_color" android:state_selected="true" />
<item android:color="@color/community_sign_in_color" android:state_selected="false" />
</selector>
- 在代码中动态设置
textView.setSelected(boolean isSelected);
网友评论