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

Cách sắp xếp mảng chuỗi (String Array) trong ListView Android

Sắp xếp String Array trong Android ListView

Hướng dẫn nhanh cách sắp xếp mảng chuỗi theo thứ tự bảng chữ cái (alphabetical order) và hiển thị lên ListView sử dụng Arrays.sort().

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

Android Studio → File → New Project.

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"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">

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

</LinearLayout>

Bước 3: Code logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    ListView list;
    // Mảng chuỗi chưa sắp xếp
    String[] array = {"2", "5", "6", "8", "0", "7", "9", "4"};

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

        list = findViewById(R.id.list);

        // Sắp xếp mảng theo thứ tự tự nhiên (alphabetical cho String)
        Arrays.sort(array);

        // Gán adapter
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, array);
        list.setAdapter(adapter);
    }
}

Kết quả

Mảng sau khi sắp xếp: ["0", "2", "4", "5", "6", "7", "8", "9"] (theo thứ tự Unicode/lexicographic).

Lưu ý: Với chuỗi số, sắp xếp lexicographic khác với sắp xếp số học. Nếu cần sắp xếp số, hãy chuyển sang Integer[] hoặc dùng Comparator tùy chỉnh.

Chạy ứng dụng

Chạy app, ListView hiển thị các chuỗi số đã được sắp xếp.

Cách sắp xếp mảng chuỗi (String Array) trong ListView Android