gpt4 book ai didi

java - 如何在 recyclerview 中制作和填充公共(public)字段?

转载 作者:搜寻专家 更新时间:2023-11-01 08:22:50 26 4
gpt4 key购买 nike

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

我已经解析它们并将各自的数据放入其 POJO 类中。问题是我想在回收站 View 中显示数据。但是这里我有三个类的共同领域是名称和权重。

所以,我想将通用列表传递给回收商 View ,并通过这样调用来填充它们:

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

任何想法将不胜感激。

最佳答案

为了实现这一点,您需要一种称为多态性 的东西,从StackOverflow 了解更多信息, Java DocsWikipedia .为了尊重这种模式,我会像这样实现这个问题:

我会创建一个 Interface有你需要的方法:

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

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

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

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

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

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

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

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

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

此外,您提到您想要一个解决方案来处理多个类。只要在每个需要显示的类中实现接口(interface),就可以拥有一百万个类。

关于java - 如何在 recyclerview 中制作和填充公共(public)字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48701039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com