如何在 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