我有一个recyclerview来展示不同的产品。我使用自定义适配器和ArrayList将数据绑定到适配器。我想按每个产品对象中的值对列表进行排序。我提到了很多问题,但我找不到合适的问题。任何人都可以使用下面给出的代码建议解决方案
我的模特课
public class Spaceship {
private int rating;
private String name,image_url,pk_id;
private int image;
public float getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image_url;
}
public void setImage(String image_url) {
this.image_url = image_url;
}
public String getPkid() {
return pk_id;
}
public void setPkid(String pk_id) {
this.pk_id = pk_id;
}
}
MainActivity代码
Spaceship model;
planList = new ArrayList<>();
try {
jsonArray = resultData.getJSONArray("packages");
for(int i=0; i<jsonArray.length();i++){
jsonObject2 = jsonArray.getJSONObject(i);
JSONObject img_object = jsonObject2.getJSONObject("images");
Iterator<String> keys= img_object.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
String valueString = img_object.getString(keyValue);
}
model = new Spaceship();
model.setName(jsonObject2.getString("vehicle_name"));
model.setRating(1);
model.setImage(img_object.getString("url1"));
model.setPkid(jsonObject2.getString("id"));
planList.add(model);
}
setAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setAdapter() {
adapter = new RecyclerAdapter(MainActivity.this, planList,MainActivity.this);
rv.setAdapter(adapter);
}
如何按“评级”值对回收者视图进行排序。
答案 0 :(得分:1)
1-实施Comparable
public class Spaceship implements Comparable {
private int rating;
private String name,image_url,pk_id;
private int image;
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image_url;
}
public void setImage(String image_url) {
this.image_url = image_url;
}
public String getPkid() {
return pk_id;
}
public void setPkid(String pk_id) {
this.pk_id = pk_id;
}
@Override
public int compareTo(Spaceship ship) {
int compareTo=((Spaceship )ship).getRating();
/* For Ascending order*/
return this.rating-compareTo;
/* For Descending order do like this */
//return compareage-this.rating;
}
}
在将列表传递给recyclerViewAdapter 之前, 2-
Collections.sort(planList);
答案 1 :(得分:0)
尝试自己修改此代码。此方法命令您的适配器中使用的Arraylist。在适配器类中使用它。 // Object Comparator ArrayList mItems
public static void order(ArrayList<ToDoItem> Items) {
Collections.sort(Items, new Comparator() {
public int compare(Object o1, Object o2) {
Boolean x1 = ((ToDoItem) o1).getStatus();
Boolean x2 = ((ToDoItem) o2).getStatus();
int sComp = x1.compareTo(x2);
if (sComp != 0)
{
return sComp;
}
else
{
Date x3 = ((ToDoItem) o1).getDeadLineDate();
Date x4 = ((ToDoItem) o2).getDeadLineDate();
return x3.compareTo(x4);
}
}
});
}
答案 2 :(得分:0)
重点是您应该已经将已排序的列表设置到适配器中并使用ArrayList
进行所有排序,然后通知适配器数据集已更改。
要通过参数比较对象,请使用Comparator
检查此stack thread和文档here
的答案