我在代码中使用Spinner控件。我希望在选择时突出显示该项目(即,该项目的背景颜色已更改)。如何实现这一目标?
答案 0 :(得分:9)
为ex:mybg.xml创建一个xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@color/anyColor" />
<item android:drawable="@android:color/transparent" />
</selector>
并在您的活动xml中
DO
<Spinner...............
android:drawSelectorOnTop="true"
android:background="@drawable/mybg"/>
答案 1 :(得分:2)
选择器:custom_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="@color/light_grey" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@color/light_grey" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@color/light_grey" />
<item android:state_selected="true" android:drawable="@color/light_grey"/>
<item android:drawable="@color/white" />
</selector>
自定义视图布局:my_simple_item
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="1"
android:padding="5dip"
android:background="@drawable/custom_selector"/>
Initialise Spinner:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_simple_item, items);
希望这有帮助