简体   繁体   中英

How to sort items in RecyclerView?

I wanted to sort the items in recyclerView. I have usernames such as 20ABC1, 20ABC2,..., 20ABC10,..etc.

I have tried answers from the related questions one of which was:

public static final Comparator<Users> BY_NAME_ALPHABETICAL = (users, t1) -> users.Username.compareTo(t1.Username);

But this does not solve the problem exactly. 20ABC10, 20ABC11,...20ABC19 comes above 20ABC2. I think it is because it checks character by character.

Any way I can solve this?

Thank you :)

My Issue got solved by using this answer Sorting Strings that contains number in Java by Bohemian where he removed the alphabets from the strings and compared the remaining ints

Collections.sort(strings, new Comparator<String>() {
    public int compare(String o1, String o2) {
        return extractInt(o1) - extractInt(o2);
    }

    int extractInt(String s) {
        String num = s.replaceAll("\\D", "");
        // return 0 if no digits found
        return num.isEmpty() ? 0 : Integer.parseInt(num);
    }
});
public Observable<User> getUsersWithBlogs() {
return Observable.fromIterable(UserCache.getAllUsers())
.filter(user -> user.blog != null && !user.blog.isEmpty())
.sorted((user1, user2) -> user1.name.compareTo(user2.name));
}

put this in your adapter

void sortByName(boolean isDescending) {
    if (mDataList.size() > 0) {
        Collections.sort(mDataList, new Comparator<Users>() {
            @Override
            public int compare(Users object1, Users object2) {
                if (isDescending)
                    return object2.getUsername().toLowerCase().compareTo(object1.getUsername().toLowerCase().trim());
                else
                    return object1.getUsername().toLowerCase().compareTo(object2.getUsername().toLowerCase().trim());
            }
        });
        notifyDataSetChanged();
    }
}

Then use it like this:

adapter.sortByName( true||false );

Using kotlin,

val comp: Comparator<Users> = Comparator { o1, o2 -> o1.Username.trim().compareTo(o2.Username.trim()) }
Collections.sort(users, comp)

Do the same for java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM