ตัวอย่างนี้สาธิตวิธี ล้าง/เคลียร์รูปภาพออกจาก ImageView โดยการตั้งค่า Background หรือ Image Resource เป็น null
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/btnClear"
android:layout_centerInParent="true"
android:background="@drawable/your_image"
android:scaleType="centerCrop" />
<Button
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:onClick="clearImage"
android:text="Clear Image" />
</RelativeLayout>
ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.kt)
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Clear ImageView Demo"
imageView = findViewById(R.id.imageView)
}
fun clearImage(view: View) {
// วิธีที่ 1: ล้าง Background Drawable (API เดิม)
// imageView.setBackgroundDrawable(null) // Deprecated
// วิธีที่ 2: แนะนำ - ล้าง Background (API 16+)
imageView.setBackgroundResource(0)
// หรือ
// imageView.background = null
// วิธีที่ 3: หากใช้ setImageResource แทน Background
// imageView.setImageResource(0)
// imageView.setImageDrawable(null)
Toast.makeText(this, "Image cleared", Toast.LENGTH_SHORT).show()
}
}
ขั้นตอนที่ 4: AndroidManifest.xml
Manifest มาตรฐาน ไม่ต้องแก้ไข
💡 ความแตกต่าง: Background vs Image Source
| Property | Method ล้าง | ใช้เมื่อไหร่ |
|---|---|---|
| android:background | setBackgroundResource(0) หรือ background = null |
รูปพื้นหลัง คงขนาด View ไว้ |
| android:src / setImageResource | setImageResource(0) หรือ setImageDrawable(null) |
รูปเนื้อหา ขนาด View อาจเปลี่ยนตามรูป |
ทดสอบ
- ใส่รูปภาพใน
res/drawable/your_image.jpg - รันแอป → จะเห็นรูปภาพเต็มหน้าจอ
- กดปุ่ม "Clear Image" → รูปจะหายไป เหลือพื้นที่ว่าง