Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบการมีอยู่ของ Element ใน Android ListView

ภาพรวม

ตัวอย่างนี้สาธิตวิธีตรวจสอบว่า Element (รายการ) มีอยู่ใน ListView แล้วหรือไม่ ก่อนเพิ่มใหม่ โดยใช้ ArrayList.contains() และอัปเดต Adapter

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 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_horizontal"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter item to add/check" />
    <Button
        android:id="@+id/buttonPanel"
        android:text="Check & Add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    EditText editQuery;
    ArrayList<String> arrayList;
    ArrayAdapter<String> adapter;

    // ข้อมูลเริ่มต้น
    String[] mobileArray = {"Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Mac OS X"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        editQuery = findViewById(R.id.edit_query);
        listView = findViewById(R.id.list);
        
        // สร้าง ArrayList จากอาร์เรย์เริ่มต้น
        arrayList = new ArrayList<>(Arrays.asList(mobileArray));
        
        // สร้าง Adapter
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
        listView.setAdapter(adapter);

        findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = editQuery.getText().toString().trim();
                
                if (input.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter text", Toast.LENGTH_SHORT).show();
                    return;
                }

                // ตรวจสอบว่ามีอยู่แล้วหรือไม่
                if (arrayList.contains(input)) {
                    Toast.makeText(MainActivity.this, "Already in list: " + input, Toast.LENGTH_LONG).show();
                } else {
                    // เพิ่มใหม่
                    arrayList.add(input);
                    // บอก Adapter ว่าข้อมูลเปลี่ยน (สำคัญ!)
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, "Added: " + input, Toast.LENGTH_LONG).show();
                }
                
                // ล้าง EditText
                editQuery.setText("");
            }
        });
    }
}

การทดสอบ

รันแอป จะแสดงรายการมือถือ 8 ชิ้น พิมพ์ "Android" คลิกปุ่ม → แสดง Toast "Already in list" พิมพ์ "Samsung" คลิกปุ่ม → เพิ่มเข้า ListView

จุดสำคัญ: notifyDataSetChanged()

หลังจากแก้ไขข้อมูลใน ArrayList (add, remove, clear) ต้องเรียก adapter.notifyDataSetChanged() เสมอ มิฉะนั้น ListView จะไม่อัปเดต

เมธอด Adapter อื่นๆ ที่ควรรู้

ปรับปรุงประสิทธิภาพสำหรับข้อมูลเยอะ

// ใช้ HashSet สำหรับ O(1) Lookup แทน ArrayList.contains() ที่เป็น O(n)
Set<String> itemSet = new HashSet<>(arrayList);

// ตรวจสอบ
if (itemSet.contains(input)) {
    // มีอยู่แล้ว
} else {
    arrayList.add(input);
    itemSet.add(input); // Sync ทั้งคู่
    adapter.notifyDataSetChanged();
}

การค้นหาแบบไม่ Case-Sensitive

// แปลงเป็น Lowercase ก่อนตรวจสอบ
String lowerInput = input.toLowerCase();
boolean exists = arrayList.stream()
    .anyMatch(item -> item.toLowerCase().equals(lowerInput));

การใช้งานจริง

  • ป้องกันรายการซ้ำใน Shopping Cart / Wishlist
  • Tag/Category Input ที่ไม่ให้ซ้ำ
  • Contact/Phone Number Validation
  • History/Recent Search ที่ไม่ซ้ำ

ListView vs RecyclerView สำหรับ Dynamic List

RecyclerView แนะนำกว่า เพราะ:

  • บังคับ ViewHolder Pattern (ประสิทธิภาพดี)
  • มี notifyItemInserted/Removed/Changed รองรับ Animation
  • LayoutManager ยืดหยุ่น (Grid, Staggered, Horizontal)
  • ItemDecoration สำหรับ Divider/Spacing
เมธอดใช้เมื่อประสิทธิภาพ
notifyDataSetChanged()ข้อมูลเปลี่ยนมาก/ไม่แน่ใจRefresh ทั้งหมด (ช้ากว่า)
notifyItemInserted(position)เพิ่ม 1 รายการ (RecyclerView)มี Animation สวย
notifyItemRemoved(position)ลบ 1 รายการ (RecyclerView)มี Animation สวย
notifyItemRangeInserted(start, count)เพิ่มหลายรายการติดกันดีกว่า notifyDataSetChanged