android里面 selector用于按钮的背景状态切换,很多年前似乎也遇到过这个失效的坑,当时没记录,百度半天也没找到解决答案,最后弄了很久找到了问题所在,这里记录下,防止下次再踩坑。
先贴失效的xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/white" />
<corners android:radius="4dp" />
<stroke android:width="@dimen/dimen_1"
android:color="@color/blue1286F1"/>
</shape>
</item>
<item android:state_selected="true">
<shape>
<solid android:color="@color/blue1286F1" />
<corners android:radius="4dp" />
</shape>
</item>
<item android:state_checked="true">
<shape>
<solid android:color="@color/blue1286F1" />
<corners android:radius="4dp" />
</shape>
</item>
</selector>
再贴正常的xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<shape>
<solid android:color="@color/blue1286F1" />
<corners android:radius="4dp" />
</shape>
</item>
<item android:state_checked="true">
<shape>
<solid android:color="@color/blue1286F1" />
<corners android:radius="4dp" />
</shape>
</item>
<item>
<shape>
<solid android:color="@color/white" />
<corners android:radius="4dp" />
<stroke android:width="@dimen/dimen_1"
android:color="@color/blue1286F1"/>
</shape>
</item>
</selector>
晃眼一看,这不就是一样的吗?其实是有差异的,默认状态那个Item必须放在最底部,否则失效,为啥呢?I don't know!