如何在recyclerview中制作和填充公共字段?

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

比方说,我在JSON文件中有一个不同结构的学生,员工和汽车类。

我已经解析它们并将相应的数据放到它的POJO类中。事情是我想在回收者视图中显示数据。但在这里我有共同的领域,三个类是名称和重量。

所以,我想转到泛型到循环器视图的列表,并通过这样调用填充它们:

tvName.setText(Object(should be generic).getName());
tvWeight.setText(Object(should be generic).getWeight());

它应该显示所有学生,员工和汽车的名称和重量。

RecyclerView看起来像

---------------------------------------------------------
CarName    
CarWeight
---------------------------------------------------------
EmplyoeeName    
EmplyoeeWeight
---------------------------------------------------------
StudentName    
StudentWeight
---------------------------------------------------------
EmplyoeeName    
EmplyoeeWeight
---------------------------------------------------------
CarName    
CarWeight
---------------------------------------------------------
CarName    
CarWeight
---------------------------------------------------------
StudentName    
StudentWeight

任何想法都将受到高度赞赏。

java android android-recyclerview
2个回答
3
投票

为了达到这个目的,你需要一些叫做polymorphism的东西,从StackOverflowJava DocsWikipedia那里学到更多东西。为了尊重这种模式,我会像这样实现这个问题:

我会创建一个Interface,它具有您需要的方法:

public interface AttributesInterface {
    String getName();
    double getWeight();
}

然后我会让每个POJO类实现该接口,看起来像这样:

public class Car implements AttributesInterface {
    private String name;
    private double weight;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public double getWeight() {
        return weight;
    }
}

在适配器中,您可以像这样存储列表。如果一个类将实现该接口,那么您将能够在该数组中添加它。因此,您将拥有一个同时包含StudentCarEmployee的数组。

private List<AttributesInterface> list = new ArrayList<>();

然后最后一步是在onBindViewHolder中,您从该数组中获取一个对象并设置相应的值。

AttributesInterface object = list.get(position);
tvName.setText(object.getName());
tvWeight.setText(String.valueOf(object.getWeight())); 

此外,您提到您希望解决方案适用于多个类。只要在每个需要显示的类中实现接口,就可以拥有一百万个类。


0
投票

您只能创建一个POJO类,并且可以添加额外的变量说类型。所以你的POJO课程将如下所示。

public class MyClassModel {

    private String type=""; // S=Student, C=Car, E=Employee
    private String  name="", weight=""; 

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }   
}

现在,您将在RecyclerviewAdapter中输入类型,以便根据数据类型编写逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.