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

Cách xóa khoảng trống không dùng trong ArrayList ListView Android

Giới thiệu

Ví dụ này demo cách loại bỏ khoảng trống (unused space) trong ArrayList khi hiển thị lên ListView, sử dụng trimToSize() và HashSet để loại trùng lặp.

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

Android Studio → File → New Project → điền thông tin.

Bước 2: 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" />

    </LinearLayout>

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

</LinearLayout>

Bước 3: 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.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    EditText name;
    ArrayAdapter<String> arrayAdapter;
    ArrayList<String> array_list;
    Set<String> set = new HashSet<>();
    ListView listView;

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

        array_list = new ArrayList<>();
        array_list.ensureCapacity(20); // Đặt dung lượng tối thiểu
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

        findViewById(R.id.refresh).setOnClickListener(v -> {
            arrayAdapter.notifyDataSetChanged();
            listView.invalidateViews();
            listView.refreshDrawableState();
        });

        findViewById(R.id.save).setOnClickListener(v -> {
            String input = name.getText().toString();
            if (!input.isEmpty()) {
                set.add(input); // HashSet tự động loại trùng lặp
                array_list.clear();
                array_list.addAll(set);
                Collections.sort(array_list); // Sắp xếp alphabet
                array_list.trimToSize(); // QUAN TRỌNG: Thu gọn dung lượng về kích thước thực tế
                arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, array_list);
                listView.setAdapter(arrayAdapter);
                Toast.makeText(this, "Đã thêm", Toast.LENGTH_LONG).show();
            } else {
                name.setError("Nhập tên");
            }
        });
    }
}

Giải thích kỹ thuật

  • HashSet: Tự động loại bỏ các phần tử trùng lặp.
  • Collections.sort(): Sắp xếp danh sách theo thứ tự alphabet.
  • array_list.trimToSize(): Giảm dung lượng (capacity) của ArrayList xuống bằng kích thước (size) thực tế, giải phóng bộ nhớ thừa.
  • ensureCapacity(20): Đặt dung lượng ban đầu để tránh resize liên tục khi thêm phần tử.

Chạy ứng dụng

Cách xóa khoảng trống không dùng trong ArrayList ListView Android

Danh sách hiển thị gọn gàng, không trùng lặp, đã sắp xếp và không có khoảng trống bộ nhớ thừa.