如何在Android的回收站视图中对卡片视图进行排序

时间:2019-03-27 17:29:05

标签: android android-recyclerview cardview

我有一些如下的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真实帐户显示为第一个cardview,将accountType显示为c,然后按照帐户类型a及其所有帐户进行帐户类型排序列表和帐户类型b及其所有帐户列表。我所有的卡都应该这样

  • 帐户类型c
  • 默认卡下方
  • 然后输入帐户类型a
  • 所有卡
  • 然后输入帐户类型b
  • 所有卡

我总是希望isDefault卡在最上面,而不管其帐户类型如何,然后我想根据cardViewaccountType排序为a,b,c等。 我要在cardView版面下方显示帐户类型,然后显示xml 如何在Bindview上实现这一目标?任何帮助表示赞赏

1 个答案:

答案 0 :(得分: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.