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

Cách lưu phần tử theo thứ tự số cho ListView Android

Giới thiệu

Ví dụ này demo cách sắp xếp ArrayList theo thứ tự số (numeric order) thay vì alphabet, sử dụng Comparator tùy chỉnh parse số từ chuỗi.

Bước 1 & 2: Tạo dự án và Giao diện

Giao diện: EditText nhập số, nút Lưu, Làm mới, ListView.

Bước 3: MainActivity.java - Sắp xếp số

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.Comparator;
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<>();
        name = findViewById(R.id.name);
        listView = findViewById(R.id.listView);

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

        findViewById(R.id.save).setOnClickListener(v -> {
            String input = name.getText().toString();
            if (!input.isEmpty()) {
                set.add(input);
                array_list.clear();
                array_list.addAll(set);

                // QUAN TRỌNG: Sắp xếp theo giá trị số (numeric sort)
                Collections.sort(array_list, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        try {
                            // Parse sang số để so sánh
                            double n1 = Double.parseDouble(o1);
                            double n2 = Double.parseDouble(o2);
                            return Double.compare(n1, n2);
                        } catch (NumberFormatException e) {
                            // Fallback: so sánh alphabet nếu không parse được
                            return o1.compareTo(o2);
                        }
                    }
                });

                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 số");
            }
        });
    }
}

Vấn đề của code gốc

Code gốc gọi Collections.max(array_list) nhưng không gán kết quả, không sắp xếp list. Phiên bản trên sửa dùng Collections.sort() với Comparator parse số.

So sánh Alphabet vs Numeric

InputAlphabet SortNumeric Sort
1, 2, 10, 31, 10, 2, 31, 2, 3, 10
5, 12, 312, 3, 53, 5, 12

Chạy ứng dụng

Cách lưu phần tử theo thứ tự số cho ListView Android

Nhập: 4, 5, 3 → Hiển thị: 3, 4, 5 (thứ tự số đúng).