Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách xóa phần tử khỏi ArrayList cho ListView trong Android

Giới thiệu

Ví dụ này minh họa cách xóa phần tử từ ArrayList và cập nhật ListView trong ứng dụng Android.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền đầy đủ thông tin cần thiết để tạo dự án mới.

Bước 2: Thiết kế giao diện (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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:hint="Nhập tên"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/save"
            android:text="Lưu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/refresh"
            android:text="Làm mới"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/delete"
            android:text="Xóa"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.andy.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;

public class MainActivity extends AppCompatActivity {
    Button save, refresh;
    EditText name;
    ArrayAdapter<String> arrayAdapter;
    private ListView listView;
    ArrayList<String> array_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        array_list = new ArrayList<>();
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

        // Khởi tạo adapter một lần
        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, array_list);
        listView.setAdapter(arrayAdapter);

        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                arrayAdapter.notifyDataSetChanged();
                listView.invalidateViews();
                listView.refreshDrawableState();
            }
        });

        findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = name.getText().toString().trim();
                if (array_list.size() > 0) {
                    if (!input.isEmpty()) {
                        boolean removed = array_list.remove(input);
                        arrayAdapter.notifyDataSetChanged();
                        if (removed) {
                            Toast.makeText(MainActivity.this, "Đã xóa", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Không tìm thấy tên", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        name.setError("Vui lòng nhập tên cần xóa");
                    }
                } else {
                    Toast.makeText(MainActivity.this, "Danh sách trống, không có gì để xóa", Toast.LENGTH_LONG).show();
                }
            }
        });

        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = name.getText().toString().trim();
                if (!input.isEmpty()) {
                    array_list.add(input);
                    arrayAdapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, "Đã thêm", Toast.LENGTH_LONG).show();
                    name.setText("");
                } else {
                    name.setError("Vui lòng nhập tên");
                }
            }
        });
    }
}

Chạy ứng dụng

Kết nối thiết bị Android thật với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn để chạy ứng dụng.

Cách xóa phần tử khỏi ArrayList cho ListView trong Android

Trong kết quả trên, chúng ta đang chèn tên vào ArrayList và hiển thị trên ListView.

Cách xóa phần tử khỏi ArrayList cho ListView trong Android

Sau khi nhấn nút Xóa, phần tử tương ứng bị loại khỏi ListView.

Sự khác biệt ArrayList vs LinkedList: ArrayList truy cập nhanh theo chỉ số (O(1)) nhưng chèn/xóa giữa chậm (O(n)). LinkedList ngược lại: chèn/xóa đầu/cuối nhanh (O(1)) nhưng truy cập chỉ số chậm (O(n)). Với ListView đơn giản, cả hai đều hoạt động tốt.