android - Selector
리스트나 버튼등에서 Normal 이미지나 포커스되었을 때 바탕화면등을 코드로 구현하기보다 XML 로 쉽게 구현할 수 있도록 되어있다.
ListView의 Adapter 를 만들면서 item_list.xml 를 만들면서 클릭시 색상을 변화주기 위해 Layout 에 android:background="@drawable/list_color" 로 설정을 하였다. 이렇게 하면 포커스나 버튼이 클릭되었을때 색상을 지정할 수 있다.
list_color.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/solid_red"/> // 클릭시
<item android:state_pressed="true" android:state_selected="false"
android:drawable="@drawable/solid_blue"/> //키패드에 의해 선택시
<item android:state_selected="false" android:drawable="@android:color/white"/> //일반적일 경우
</selector>
<item android:state_selected="true" android:drawable="@drawable/solid_red"/> // 클릭시
<item android:state_pressed="true" android:state_selected="false"
android:drawable="@drawable/solid_blue"/> //키패드에 의해 선택시
<item android:state_selected="false" android:drawable="@android:color/white"/> //일반적일 경우
</selector>
solid_red 등은 values -- colors.xml 에 drawable 형태로 설정하였다.
<resources>
<drawable name="solid_red">#f00</drawable>
<drawable name="solid_blue">#0000ff</drawable>
<drawable name="solid_green">#f0f0</drawable>
<color name="testcolor1">#808080</color>
<color name="testcolor2">#ababab</color>
...
</resources>
text_color.xml
<resources>
<drawable name="solid_red">#f00</drawable>
<drawable name="solid_blue">#0000ff</drawable>
<drawable name="solid_green">#f0f0</drawable>
<color name="testcolor1">#808080</color>
<color name="testcolor2">#ababab</color>
...
</resources>
text_color.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@color/testcolor1"/>
<item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
<item android:state_enabled="false" android:color="@color/testcolor3" />
<item android:state_active="true" android:color="@color/testcolor4" />
<item android:color="@color/testcolor5"/>
</selector>
<item android:state_focused="true" android:color="@color/testcolor1"/>
<item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
<item android:state_enabled="false" android:color="@color/testcolor3" />
<item android:state_active="true" android:color="@color/testcolor4" />
<item android:color="@color/testcolor5"/>
</selector>
XML에서의 <selector> 는 코드 레벨에서는 StateListDrawable 개체로 변형된다.
참고)
http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html
http://developer.android.com/guide/topics/resources/drawable-resource.html
'scrap > Android' 카테고리의 다른 글
AlertDialog (0) | 2011.02.06 |
---|---|
ListView, ListAdapter (0) | 2011.02.04 |
Listview drag&drop (0) | 2011.02.04 |
OutOfMemoryError (0) | 2011.02.04 |
Android tip 100 (1) | 2011.02.04 |