如何在android中的recycleler视图中对卡片视图进行排序

问题描述 投票:-2回答:1

我有一些API响应如下:

 [      
        {
            accountType: a,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas1
        }, {
            accountType: b,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas2
        }, {
            accountType: c,
            accountId: 1,
            accountStatus: active,
            isDefault: true,
            accountName: texas4
        }, {
            accountType: a,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas5
        }, {
            accountType: b,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas6
        },
        {
            accountType: a,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas7
        }, {
            accountType: b,
            accountId: 1,
            accountStatus: active,
            isDefault: false,
            accountName: texas9
        }  ]

我希望isDefault真实帐户显示为第一个cardviewaccountType作为c然后帐户类型排序应该像帐户类型a和它的所有帐户列表和帐户类型b及其所有帐户列表。我的所有卡片应该是这样的

  • 帐户类型c
  • 低于默认卡
  • 然后帐户类型a
  • 所有卡片
  • 然后帐户类型b
  • 所有卡片

我总是希望isDefault卡在顶部而不管它的帐户类型然后我想基于cardView排序accountType作为a,b,c等我在cardView布局中显示帐户类型然后xml如何在Bindview上实现这一点?任何帮助表示赞赏

android android-recyclerview cardview
1个回答
0
投票

RecyclerView将按照您将它们传递给适配器的确切顺序显示元素。您需要做的是按照您希望它们的顺序重新排列元素,然后将它们传递给适配器,以便显示它们。一个基于您输入的简单示例

//This is just a data class for our API response
class Account {
    String accountType;
    int accountId;
    boolean accountStatus;
    boolean isDefault;
    String accountName;
}

//Lets say that you have your API response in a list as such
List<Account> accountList = new ArrayList<>();
accountList.add(/*Response from API*/);

//Now we create a sorted list based on your rules
List<Account> sortedAccountList = new ArrayList<>();

//First we need the isDefault account
for (Account account : accountList) {
    if (account.isDefault) {
        sortedAccountList.add(account);
        accountList.remove(account);
        break;
    }
}

//Now we add all 'c' type accounts
for (Account account : accountList) {
    if (account.accountType.equals("c")) {
        sortedAccountList.add(account);
        accountList.remove(account);
    }
}

//Do the same as above for the other account types. You can also apply more rules as per your needs.
© www.soinside.com 2019 - 2024. All rights reserved.