단비의 개발블로그

[Android] Button 클릭 효과 주기 (버튼 누르는 효과, XML) 본문

Android

[Android] Button 클릭 효과 주기 (버튼 누르는 효과, XML)

단비냥 2019. 8. 6. 22:43
반응형

오늘은 간단하지만 잊어버리기 쉬운 버튼 클릭 효과에 대해 포스팅 해보겠습니다!

 

바로 본론으로 들어가서

 

먼저 res/drawable 폴더에 새 resource 파일을 생성해주세요

 

New-Drawable resource file

drawable/button_back.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item
        android:state_pressed="true"
        android:drawable="@drawable/button_back_pressed"/>
 
    <item
        android:state_window_focused="false"
        android:state_enabled="true"
        android:drawable="@drawable/button_back_normal"/>
 
    <item
        android:state_enabled="true"
        android:drawable="@drawable/button_back_normal"/>
 
    <item
        android:state_enabled="false"
        android:drawable="@drawable/button_back_disabled"/>
 
</selector>
 
 

맨 윗줄 state_pressed="true" 에는 눌렀을 때의 상태,

두, 세번째 item은 누르지 않은 (보통의) 버튼 상태,

마지막 state_enabled="false" 에는 버튼이 비활성화 되었을 때의 drawable을 넣어줍니다. 

 

drawable/button_back_pressed.xml

1
2
3
4
<shape android:shape="rectangle"
    <solid android:color="@color/colorPrimaryDark" />
</shape>
 
csv

item에 drawable 속성으로 넣어준 xml 파일은 이렇게 작성해주면 됩니다.

android:color 속성 안에 원하는 색상을 넣어주시면 됩니다.

위에서 쓰인 다른 2개의 drawable도 같은 방식으로 색만 바꿔주시면 됩니다.

 

layout/activity_main.xml

1
2
3
4
 <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/button_back"/>
 

이렇게 작성한 drawable 파일을 layout에서 background로 넣어주면 끝입니다. 

 

간단한 예제였습니다. 감사합니다!

반응형
Comments