今天写一个用两个自定义的TextView控制ViewPager的时候,想实现点击TextView处于选中状态,
selector就选中<item>中的state_selected所对应的图片。
selector中按往常的习惯这样写的
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/icon_selfinfo_pressed" android:state_selected="true" /> <item android:drawable="@drawable/icon_selfinfo_pressed" android:state_pressed="true" /> <item android:drawable="@drawable/icon_selfinfo_normal" /> </selector>但是我在使用的时候设置tv.setSelected(true)的时候,始终只是按下一个状态,弹起恢复原来的状态,达不到我想要的selected状态。
分析了很多原因,有说按顺序从上到下选匹配的:
During each state change, the state list is traversed top to bottom and the first item that matches the current state will be used—the selection is not
based on the "best match," but simply the first item that meets the minimum criteria of the state.
但是我做过测试,如上讲selected状态放到最上面,但是还是没有setSeleted(true)的效果。估计还是匹配不了吧
估计在pressed和selected状态时候,我们点击匹配的都是pressed。
后面转换了下思想,没必要用state_pressed属性,直接这样写达到了目的:
<item android:drawable="@drawable/icon_selfinfo_pressed" android:state_selected="true" /> <item android:drawable="@drawable/icon_selfinfo_normal" android:state_selected="false" /> <item android:drawable="@drawable/icon_selfinfo_normal" />
而且state_pressed和state_selected一起使用本身就觉得很奇怪,
到底是要pressed的点击一个状态,弹起呈现另一个状态,还是要selected的点击就一直选中状态?
归根到底两个一起使用不明确,我自己感觉意义也不大。
于是今天到此为止,总结下<selector>的用法就结束吧。