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

Cách xóa tất cả phần tử khỏi LinkedList cho ListView trong Android

Giới thiệu

Ví dụ này minh họa cách xóa toàn bộ phần tử từ LinkedList 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" />

        <Button
            android:id="@+id/deleteall"
            android:text="Xóa TẤT CẢ"
            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>

Giao diện có thêm nút Xóa TẤT CẢ (deleteall) để xóa toàn bộ danh sách.

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.LinkedList;

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

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

        link_list = new LinkedList<>();
        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, link_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.deleteall).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (link_list.size() > 0) {
                    link_list.clear();
                    arrayAdapter.notifyDataSetChanged();
                    Toast.makeText(MainActivity.this, "Đã xóa tất cả", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Danh sách đã trống", Toast.LENGTH_LONG).show();
                }
            }
        });

        findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = name.getText().toString().trim();
                if (link_list.size() > 0) {
                    if (!input.isEmpty()) {
                        boolean removed = link_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", 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()) {
                    link_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 tất cả phần tử khỏi LinkedList cho ListView trong Android

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

Cách xóa tất cả phần tử khỏi LinkedList cho ListView trong Android

Sau khi nhấn nút Xóa TẤT CẢ, toàn bộ danh sách bị xóa sạch.

Phương thức clear(): LinkedList.clear() xóa tất cả phần tử trong O(1) thời gian vì chỉ cần đặt head/tail về null. Luôn gọi notifyDataSetChanged() sau khi xóa để cập nhật UI.