简体   繁体   English

如何在RecyclerView中对项目排序?

[英]How to sort items in RecyclerView?

I wanted to sort the items in recyclerView. 我想对recyclerView中的项目进行排序。 I have usernames such as 20ABC1, 20ABC2,..., 20ABC10,..etc. 我有用户名,例如20ABC1、20ABC2,...,20ABC10等。

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. 20ABC10、20ABC11,... 20ABC19高于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 通过使用此答案解决了我的问题由Bohemian 在Java中对包含数字的字符串进行了排序,他从字符串中删除了字母并比较了剩余的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, 使用kotlin,

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

Do the same for java. 对Java执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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