버튼을 누르고 있을 동안 색을 바꿔주는 효과를 넣고 싶을 때가 있습니다.
그럴 때 selector를 이용하게 되는데 주의할 점은 TextColor와 background 색을 변경하는 것이 조금 다릅니다.
TextColor는 res의 color 디렉토리를 생성하여 그 안에 selector를 넣어주어야 하고
background는 res의 drawable 디렉토리 안에 selector를 넣어주어야 합니다.


background 색을 변경할 


button_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/bg_select"/>
    <item android:state_focused="true" android:drawable="@drawable/bg_select"/>
    <item android:state_pressed="true" android:drawable="@drawable/bg_select"/>
    <item android:drawable="@drawable/bg"/>
</selector>

TextColor를 변경할 때


text_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/colorBlue"/>
    <item android:state_focused="true" android:color="@color/colorBlue"/>
    <item android:state_pressed="true" android:color="@color/colorBlue"/>
    <item android:color="@color/colorWhite"/>
</selector>



colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorWhite">#FFFFFF</color>
    <color name="colorBlue">#2196F3</color>
    <drawable name="bg_select">#2196F3</drawable>
    <drawable name="bg">#EEEEEE</drawable>
</resources>

activity_main.xml

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextViewTest"
    android:textColor="@color/text_selector"/>
 
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/button_selector"
    android:text="ButtonTest"/>




+ Recent posts