Android sort ListView alphabetically

前端 未结 8 1145
后悔当初
后悔当初 2020-12-05 03:10

So I\'m trying to sort a simple ArrayAdapter for ListView. Here\'s what I\'ve tried:

ListView lv;
String[] months = {
        \"January\",
              


        
相关标签:
8条回答
  • 2020-12-05 03:26

    You didn't called setAdapter(adapter), after sorting your items.

    Use like below

    adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, list);
    lv.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    

    instead of

    adapter.clear(); // Useless 
    adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, list);
    adapter.notifyDataSetChanged();
    
    0 讨论(0)
  • 2020-12-05 03:28

    To sort a list, you need to use a Comparator. You need to sort the underlying collections using a comparator that does alphabetical sorting and then notify the list to update itself.

    Here's an example of doing this using an ArrayAdapter : https://stackoverflow.com/a/8920348/1369222

    0 讨论(0)
  • 2020-12-05 03:31

    Android sort listview alphabetically.

    listAdapter = new AppsAdapter(MainActivity.this,R.layout.content_layout,appList);
            final Collator col = Collator.getInstance();
            listAdapter.sort(new Comparator<ApplicationInfo>() {
                @Override
                public int compare(ApplicationInfo lhs, ApplicationInfo rhs) {
                    return col.compare(lhs.loadLabel(packageManager),rhs.loadLabel(packageManager));
                }
            });
    
    0 讨论(0)
  • 2020-12-05 03:34

    Here is the trick...

    private void sortAscending () {
        List<String> sortedMonthsList = Arrays.asList(months);
        Collections.sort(sortedMonthsList);
    
        months = (String[]) sortedMonthsList.toArray();
    }
    

    And for sortAscending, call

    sortAscending();
    adapter.notifyDatasetChanged();
    

    Similarly, you can implement custom Comparator for sort descending as well...

    Hope this helps...:)

    0 讨论(0)
  • 2020-12-05 03:39
    Comparator<String> ALPHABETICAL_ORDER1 = new Comparator<String>() { 
        public int compare(String object1, String object2) {
            int res = String.CASE_INSENSITIVE_ORDER.compare(object1.toString(), object2.toString()); 
            return res;
        }
    }; 
    
    Collections.sort(your array name, ALPHABETICAL_ORDER1);
    
    0 讨论(0)
  • 2020-12-05 03:41
    1. Sort your array.
    2. Recreate adapter.
    3. Apply adapter to listview.
    0 讨论(0)
提交回复
热议问题