개발 공부/안드로이드

[android] ripple drawable 버튼 클릭시 효과

yong_DD 2022. 4. 12. 22:50

버튼을 클릭할 때 클릭한 느낌을 주도록 효과를 주고 싶을 때! 배경색을 바꾸고 싶을 때!

ripple을 사용하면 버튼 클릭시 간단하게 효과를 줄 수 있다.

터치한 부분에 따라 퍼져나가듯이 반응을 한다.

<상단 예시 코드>

//color
<color name="pressBlue">#9ADFED</color>
<color name="blue">#286189</color>

//Drawable
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/pressBlue"> //클릭시 변경할 색 부분
    <item android:id="@android:id/background"> 
        <shape>
            <solid android:color="@color/blue"/> //기본 색 부분
            <corners android:radius="10dp"/>
        </shape>
    </item>
</ripple>
//layout
<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">

    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/button_back"
        android:text="Hello World!"
        android:textColor="@color/white"
        android:textSize="18dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Q.음영(shadow)을 없애고 싶다면?

- xml 버튼에 추가해주면 끝!

android:stateListAnimator="@null"