当我们设置background属性的时候可以设置background="@color/black"
也可以设置 background="@drawable/selector"
然后selector我们可以这样设置
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 没有焦点时的背景图片 --> <item android:drawable="@color/colorPressed" android:state_pressed="true"/> <item android:drawable="@color/colorPressed" android:state_focused="true"/> <item android:drawable="@color/colorPressed" android:state_selected="true"/> <item android:drawable="@color/black" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/> </selector>
但是当我们设置了属性来设置这个颜色的时候就会遇到崩溃比如我们这样
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 没有焦点时的背景图片 --> <item android:drawable="@color/colorPressed" android:state_pressed="true"/> <item android:drawable="@color/colorPressed" android:state_focused="true"/> <item android:drawable="@color/colorPressed" android:state_selected="true"/> <item android:drawable="?attr/backgroundColorValue" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/> </selector>
运行的话会直接崩溃,报错的原因是无法获取到对应的drawable对象,至于为什么无法将颜色转换成对应的drawable我也不清楚,既然不能转换那我们可以手动转换解决方案:手动创建一个shape.xml,如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="?attr/backgroundColorValue" /> </shape>
然后我们再到selector中引用这个drawable就可以了
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 没有焦点时的背景图片 --> <item android:drawable="@color/colorPressed" android:state_pressed="true"/> <item android:drawable="@color/colorPressed" android:state_focused="true"/> <item android:drawable="@color/colorPressed" android:state_selected="true"/> <item android:drawable="@drawable/shape" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/> </selector>
时间: 2024-10-06 12:07:59