코딩스토리

[Android/안드로이드] Button Select Event - 버튼 눌림 효과 본문

Android/유용한 기술

[Android/안드로이드] Button Select Event - 버튼 눌림 효과

라크라꾸 2020. 7. 4. 03:30

버튼을 클릭했을 때 버튼이 눌릴 때 색이 변한다던가, 이미지가 변하는 경우가 있습니다.

색이 변하기 위해서는 먼저 res폴더 안에 drawable에 파일을 추가해줘야 합니다. 

 

파일을 생성하게 되면 코드를 작성합니다. 저는 "button_back.xml"이라고 생성했습니다.

 

button_back.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="false">
        <shape>
            <solid android:color="#000"/>
            <corners
                android:radius="5sp"/>
        </shape>
    </item>

    <item android:state_pressed="true" >
        <shape xmlns:android="http://schemas.android.com/apk/res/android" >
            <solid android:color="#999"/>
            <corners
                android:radius="5sp"/>
        </shape>
    </item>

</selector>

 

버튼을 생성해 줄때 background속성에 방금 만든 button_back을 넣어줍니다.

 

 <Button
        android:id="@+id/btn1"
        android:background="@drawable/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

 

selector xml의 이벤트는 다음과 같은 속성을 주로 사용합니다.

 

android:state_pressed = 객체를 누를 때 (ex : 버튼을 터치하거나 클릭 할 때)이 항목을 사용해야하는 경우 "true"; 이 항목을 누르지 않은 기본 상태로 사용해야하는 경우 "false"입니다.

 

android:state_checked = 개체를 확인할 때 이 항목을 사용해야하는 경우 "true"입니다. 객체를 체크하지 않은 상태에서 사용해야하는 경우 "false"입니다.

 

android:state_enabled = 개체가 활성화되어있을 때이 항목을 사용해야하는 경우 "true"(터치 / 클릭 이벤트 수신 가능); 개체를 사용할 수 없을 때 사용해야하는 경우 "false"입니다.

 

android:state_focused = 버튼이 강조 표시 될 때와 같이 객체에 포커스가있을 때이 항목을 사용해야하는 경우"true "; 이 항목을 초점이없는 기본 상태로 사용해야하는 경우 "false"입니다.

android:state_selected = 개체를 선택할 때 (ex : 탭을 열 때와 같이)이 항목을 사용해야하는 경우 "true"; 개체를 선택하지 않은 상태에서이 항목을 사용해야하는 경우 "false"입니다.

Comments