如何在 Android listview 中對字串陣列進行排序?
本示例演示如何在 Android listview 中對字串陣列進行排序。
步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟 2 − 向 res/layout/activity_main.xml 新增以下程式碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://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"> </ListView> </LinearLayout>
在程式碼中,我們已獲取 listview 來顯示排序的陣列
步驟 3 − 向 src/MainActivity.java 新增以下程式碼
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
ListView list;
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);
Arrays.sort(array);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array);
list.setAdapter(adapter);
}
}讓我們嘗試執行你的應用程式。我假設你已將真正的 Android 移動裝置連線到電腦。要從安卓工作室執行應用,請開啟該專案的活動檔案之一,然後單擊工具欄上的執行
圖示。按選項選擇你的移動裝置,然後檢視移動裝置上顯示的預設螢幕 –

在上面的結果中,我們展示了一個排序的陣列。
單擊 此處 下載專案程式碼
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP