如何按字母顺序对列表视图项进行排序?

时间:2018-12-12 05:52:48

标签: android listview

我有一个列表视图,我想按字母顺序排序。我该怎么办?

public class AppDrawer extends AppCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    getSupportActionBar().hide();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_drawer);
    ListView userInstalledApps = (ListView) findViewById(R.id.installed_app_list);
    List<AppList> installedApps = getInstalledApps();
    AppAdapter installedAppAdapter = new AppAdapter(this, installedApps);
    userInstalledApps.setAdapter(installedAppAdapter);
}

private List<AppList> getInstalledApps() {
    List<AppList> res = new ArrayList<AppList>();
    List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);
        if ((isSystemPackage(p) == false)) {
            String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
            Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
            res.add(new AppList(appName, icon));
        }
    }
    return res;
}

private boolean isSystemPackage(PackageInfo pkgInfo) {
    return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true : false;
}

3 个答案:

答案 0 :(得分:0)

您可以使用Comparator对列表进行排序。

 List<AppList> installedApps = getInstalledApps();

    Collections.sort(installedApps , new Comparator<AppList>() {
        public int compare(AppList v1, AppList v2) {
            return v1.getAppName().compareTo(v2.getAppName());
        }
    });

或者如果您使用的是Java 8:

list.sort(String::compareToIgnoreCase);

答案 1 :(得分:0)

您可以使用比较器对列表进行排序。如下更改您的getInstalledApps()方法。

private List<AppList> getInstalledApps() {
    List<AppList> res = new ArrayList<AppList>();
    List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);
        if ((isSystemPackage(p) == false)) {
            String appName = p.applicationInfo.loadLabel(getPackageManager()).toString();
            Drawable icon = p.applicationInfo.loadIcon(getPackageManager());
            res.add(new AppList(appName, icon));
        }
    }
    Collections.sort(res, new Comparator<AppList>() {
        @Override
        public int compare(AppList o1, AppList o2) {
            return o1.getAppName().compareTo(o2.getAppName());  // use your getter for getting app name you are setting.
        }
    });
    return res;
}

答案 2 :(得分:0)

List接口的

sort方法是可变操作。您的列表将被修改,并且使用Java 8 Streams更好地破坏List的order属性

List.stream()。sorted()。collect(Collectors.toList());

以排序方式传递比较器并获取列表。