TIL231222 D25 selector

jericho·2023년 12월 22일

TIL

목록 보기
25/62

오늘은 공부를 별로 하지 못했다..
집에 수도관이 얼어서 그걸 해결하느라고 내내 고생했다...
selector나 간단하게 알아보자.

selector

<!-- activity_home.xml - ConstraintLayout -->
android:background="@drawable/selector_button"


<!-- drawable - selector_button.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/dark_yellow" />
            <corners android:radius="20dp" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/yellow" />
            <corners android:radius="20dp" />
        </shape>
    </item>

</selector>


<!-- activity_home.xml - ConstraintLayout - ImageView -->
android:src="@drawable/selector_btn_imoji"


<!-- drawable - selector_btn_imoji.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/imoji_astonished" android:state_focused="true" />
    <item android:drawable="@drawable/imoji_scream" android:state_pressed="true" />
    <item android:drawable="@drawable/imoji_smile" />
</selector>

이렇게 사용한다.

버튼처럼 활용하려면 findViewById<ConstraintLayout>으로 레이아웃 아이디를 가져와서 똑같이 setOnClickListener로 리스너를 만들어주면 된다.

주의할 점은 셀렉터에서 위쪽 조건부터 차례로 맞추는 식이라서 상태 조건이 없는 기본값을 맨 밑에 둬야 한다.

단순한 속성 변경은 xml의 selector로 처리하는 편이 간단하다.

0개의 댓글