selector로 버튼 꾸미기 in Android Studio
이 글은 기존 블로그의 원문에서 가져왔습니다. 원문 작성일: 2021-10-02
1. selector_button.xml
<?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>
3, 9 - android:state_pressed=""로 버튼이 눌러진 상태인지 아닌지에 대한 boolean 값을 전달해준다.
5, 11 - solid로 버튼이 눌러졌을 때와 평상시의 버튼의 색을 정한다.
6, 12 - corners로 버튼의 꼭짓점의 모양을 정할 수 있다.
2. selctor_button_img.xml
<?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>
3, 4 - 위에서 처럼 각각의 상황에 버튼에 적용할 이미지를 전달한다.
3. activity_main.xml
<?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>
12, 22 - background로 만들었던 selector을 연결한다. (하지만 여기까지만 하면 themes.xml에 정의된 기본 테마에 의해서 의도대로 적용되어보이지 않는다.)
13~14 - backgroundTint에 대한 설정들을 위 코드와 같이 해주면 의도대로 작동할 것이다.