selector中的state_selected不起作用:注意state_activated状态
selector中的state_selected不起作用:注意state_activated状态
项目中遇到的问题。N个功能的一排图标,放置到一个ListView中去显示,点击不同图标做相应功能的设置,为让用户更清楚明了知道现在设置是哪个功能,所以要加一个选择中的功能。
大体实现步骤
1.ListView中的图标在drawable中写出selector,该selector文件中列出了android:state_pressed的图片资源、state_selected的图片资源。
2.ListView的onItemClickedListener监听里,针对当前选择的view,调用view.selected(true)
遇到的问题
在ListView中的某个功能图标点击时,点击下去显示的是state_pressed的图片资源,但手离开后又变会了默认的图片资源。
解决问题
开始猜测是画面中存在的其他控件,如Button、SeekBar等抢占了焦点所以导致ListView中ListItem无法显示selected状态。
在布局文中控制处ListView外的其他控件全都加上android:focusable="true"使其不可获得焦点。
这样的结果并没解决问题,需求中想要的selected状态的图片还是没显示出来。
后来在StackOverflow网站中,找到了state_activated状态,于是就在selector的xml文件中加入了state_activated="true"的控制,结果问题解决了。
官网上的state_activated
定义在android.graphics.drawable.StateListDrawable类中对xml属性的android:state_activated做了如下说明
android:state_activated
State value for StateListDrawable, set when a view or its parent has been "activated" meaning the user has currently marked it as being of interest. This is an alternative representation of state_checked for when the state should be propagated down the view hierarchy.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol state_activated.
android.R.attr中的说明
public static final int state_activated
Added in API level 11
State value for StateListDrawable, set when a view or its parent has been "activated" meaning the user has currently marked it as being of interest. This is an alternative representation of state_checked for when the state should be propagated down the view hierarchy.
Must be a boolean value, either "true" or "false".
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
Constant Value: 16843518 (0x010102fe)
注意事项
selector.xml中的state_activated状态属性必须在androidAPI-11及以上版本使用。