DrZOU 2017-12-21
在android 的TV开发中,有时候需要在GridView或ListView中每行显示RadioGroup,RadioGroup中包含RadioButton,又需要设置RadioButton的选择图标我们会写如下代码:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/radio_checked" android:state_checked="true" /> <item android:drawable="@mipmap/radio_hover" android:state_focused="true" /> <item android:drawable="@mipmap/radio_hover" android:state_selected="true" /> <item android:drawable="@mipmap/radio_checked" android:state_pressed="true" /> <item android:drawable="@mipmap/radio_uncheck" android:state_selected="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_checked="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_focused="false" /> <item android:drawable="@mipmap/radio_uncheck" /> </selector>
这样在电视上(盒子或电视上,模拟器上没有这个问题),会发现ListView或GridView的第一行中RadioGroup下面的RadioButton全部被选中,这是因为如果ListView将焦点优先权给了子View时,ListView中的第一行中的元素就会被选中,我们修改代码如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/radio_checked" android:state_pressed="true" /> <item android:drawable="@mipmap/radio_hover" android:state_focused="true" /> <item android:drawable="@mipmap/radio_checked" android:state_checked="true" /> <item android:drawable="@mipmap/radio_uncheck" android:state_selected="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_checked="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_focused="false" /> <item android:drawable="@mipmap/radio_uncheck" /> </selector>
这样上面的问题解决了,又会发现一个新问题,当RadioButton按下时,显示checked的图标,当松开时,就会显示获取焦点的图标,而不是check的图标,只有当这个RadioButton失去焦点时,才又会显示checked的图标,修改代码如下,就没有问题了:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/radio_checked" android:state_checked="true" /> <item android:drawable="@mipmap/radio_checked" android:state_pressed="true" /> <item android:drawable="@mipmap/radio_hover" android:state_focused="true" /> <item android:drawable="@mipmap/radio_uncheck" android:state_selected="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_checked="false" /> <item android:drawable="@mipmap/radio_uncheck" android:state_focused="false" /> <item android:drawable="@mipmap/radio_uncheck" /> </selector>