ตัวอย่างนี้สาธิตวิธี ซ่อน/ลบเส้นคั่น (Divider) ระหว่างรายการใน ListView โดยการตั้งค่า divider = null หรือ dividerHeight = 0
ขั้นตอนที่ 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"
android:paddingStart="4dp"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
ขั้นตอนที่ 3: โค้ดหลัก (MainActivity.kt)
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val phones = arrayOf("Samsung", "iPhone", "Nokia", "Alcatel", "BlackBerry", "Oppo", "Sony")
private lateinit var listView: ListView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Remove ListView Divider"
listView = findViewById(R.id.listView)
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, phones)
listView.adapter = adapter
// 🔑 จุดสำคัญ: ลบ Divider
listView.divider = null
// หรือใช้: listView.dividerHeight = 0
}
}
🔧 วิธีอื่นๆ
| วิธี | Code | คำอธิบาย |
|---|---|---|
| XML Attribute | android:divider="@null" |
ตั้งใน Layout XML ได้เลย |
| XML Attribute | android:dividerHeight="0dp" |
ตั้งความสูงเป็น 0 |
| Code - null divider | listView.divider = null |
ใช้ Drawable null |
| Code - height 0 | listView.dividerHeight = 0 |
ตั้งความสูง 0 pixel |
| Custom Divider | listView.divider = ContextCompat.getDrawable(this, R.drawable.custom_divider) |
ใช้ Drawable ส่วนตัว |
🎨 สร้าง Custom Divider (res/drawable/custom_divider.xml)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="1dp" />
<solid android:color="#DDDDDD" />
</shape>
💡 RecyclerView Alternative
RecyclerView ไม่มี Divider ติดมาด้วย ต้องเพิ่มเอง:
recyclerView.addItemDecoration(
DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
)
// หรือ Custom
recyclerView.addItemDecoration(CustomDividerItemDecoration(context))
ขั้นตอนที่ 4: AndroidManifest.xml
Manifest มาตรฐาน
ทดสอบ
- รันแอป → แสดงรายการโทรศัพท์ 7 รายการ
- ไม่มีเส้นคั่นระหว่าง Item
- ลอง Comment บรรทัด
listView.divider = null→ จะเห็นเส้นคั่นกลับมา