ภาพรวม
บทความนี้สาธิตการสร้างไอคอน X/Close แบบมีวงกลมพื้นหลัง ด้วย Vector Drawable
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_marginTop="30dp"
tools:context=".MainActivity">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/close_icon" />
</LinearLayout>
ขั้นตอนที่ 3: Vector Drawable (res/drawable/close_icon.xml)
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="https://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- วงกลมพื้นหลังสีแดง -->
<path
android:fillColor="#FF0000"
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z" />
<!-- เครื่องหมาย X สีขาว -->
<path
android:fillColor="#FFFFFF"
android:pathData="M12,5.5L7.5,10 9,11.5 12,8.5 15,11.5 16.5,10 12,5.5zM12,18.5L7.5,14 9,12.5 12,15.5 15,12.5 16.5,14 12,18.5z" />
</vector>
Path Data แบบแยก (เข้าใจง่ายกว่า)
<vector ...>
<!-- วงกลม -->
<path android:fillColor="#FF0000"
android:pathData="M12,2A10,10 0 1,1 12,22A10,10 0 1,1 12,2Z" />
<!-- เส้นทแยง \ -->
<path android:fillColor="#FFFFFF"
android:pathData="M7,7 L17,17 M17,7 L7,17"
android:strokeWidth="2"
android:strokeLineCap="round" />
</vector>
ใช้ Material Icons (แนะนำ)
แทนที่จะวาดเอง ให้ใช้ Material Icons:
- ใน XML:
android:drawable="@drawable/ic_close_24" - Vector Asset Studio: New → Vector Asset → Material Icons → search "close"
- Dependency:
implementation "androidx.compose.material:material-icons-extended"(Compose)
การใช้งานทั่วไป
- ปุ่มปิด Dialog/Bottom Sheet
- ปุ่มลบ Item ใน List
- Clear text ใน EditText
- Dismiss Snackbar/Toast
ทดสอบ
รันแอป จะเห็นวงกลมสีแดงพร้อมเครื่องหมาย X สีขาวตรงกลาง