---
# System prepended metadata

title: '`ImageButton` 點擊時套用自定義背景'
tags: [實作相關]

---

`ImageButton` 點擊時套用自定義背景
===
* `layout/YOUR_LAYOUT.xml`
```xml=
<ImageButton
    android:id="@+id/iBtn_userProfile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    android:background="@drawable/button_selector"/>
            
```

* `drawable/button_selector.xml`
```xml=
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--     點擊, 改變背景形狀, 套用 shape 檔     -->
    <item
        android:state_pressed="true"
        android:drawable="@drawable/shape_pressed" />
        
    <!--     未點擊, 透明背景, 直接設為透明     -->
    <item
        android:state_pressed="false"
       android:drawable="@android:color/transparent" />
       
</selector>
```
* `drawable/shape_pressed.xml`
```xml=
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#7FE6E3E1" />
    <padding
        android:top="8dp"
        android:right="8dp"
        android:bottom="8dp"
        android:left="8dp" />
    <corners android:radius="30dp" />
</shape>
```

## Ref.
[【Android 小知識】shape 元件樣式](http://learnexp.tw/%E3%80%90android-%E5%B0%8F%E7%9F%A5%E8%AD%98%E3%80%91shape-%E5%85%83%E4%BB%B6%E6%A8%A3%E5%BC%8F/)

###### tags: `實作相關`