Android App

selector로 버튼 꾸미기 in Android Studio

YunSeong 2021. 10. 2. 01:46
728x90
반응형

https://youtu.be/9E0WwR_6P9w

 

1. selector_button.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#EF9A9A"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape>
            <solid android:color="#E6EE9C"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>
</selector>
cs

3, 9 - android:state_pressed=""로 버튼이 눌러진 상태인지 아닌지에 대한 boolean 값을 전달해준다.

5, 11 - solid로 버튼이 눌러졌을 때와 평상시의 버튼의 색을 정한다.

6, 12 - corners로 버튼의 꼭짓점의 모양을 정할 수 있다.


2. selctor_button_img.xml

1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/ic_launcher_background"></item>
    <item android:state_pressed="false" android:drawable="@drawable/ic_launcher_foreground"></item>
</selector>
cs

3, 4 - 위에서 처럼 각각의 상황에 버튼에 적용할 이미지를 전달한다.


3. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="168dp"
        android:layout_height="37dp"
        android:background="@drawable/selector_button"
        app:backgroundTint="#00000000"
        app:backgroundTintMode="add"
        android:text="예에에ㅔㅔ"
                     ...         />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="184dp"
        android:background="@drawable/selector_button_img"
                    ...               />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

12, 22 - background로 만들었던 selector을 연결한다. (하지만 여기까지만 하면 themes.xml에 정의된 기본 테마에 의해서 의도대로 적용되어보이지 않는다.)

13~14 - backgroundTint에 대한 설정들을 위 코드와 같이 해주면 의도대로 작동할 것이다.

728x90
반응형