我有两个名为Buyer和Car的模型,以及一个名为custom_row的自定义布局来显示ListView的行.
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList buyers;
public CustomAdapter(Context c, ArrayList buyers) {
this.c = c;
this.buyers = buyers;
}
@Override
public int getCount() {
return buyers.size();
}
@Override
public Object getItem(int position) {
return buyers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(c).inflate(R.layout.custom_row, parent, false);
}
TextView tvBuyerName = (TextView) convertView.findViewById(R.id.tvBuyerName);
TextView tvCarModel = (TextView) convertView.findViewById(R.id.tvCarModel);
final Buyer b = (Buyer) this.getItem(position);
tvBuyerName.setText(b.getBuyerName());
return convertView;
}
}
到目前为止,我只完成了上面的代码,而且我只能显示买家的名字.如何在ArrayList中创建另一个引用来建模Car,这样我就可以在同一个ListView中获取和显示来自模型买家和模型Car的信息?
解决方法:
一种方法是创建一个包含Car& Car的模型.买方数据.
由此你可以从同一个arraylist访问汽车和买家.
另一个是将两个arraylist(carList& buyerList)传递给适配器的构造函数.
ArrayList buyers;
ArrayList cars;
public CustomAdapter(Context c, ArrayList buyers, ArrayList cars) {
this.c = c;
this.buyers = buyers;
this.cars= cars;
}
然后
final Buyer b = (Buyer) buyers.getItem(position);
tvBuyerName.setText(b.getBuyerName());
final Car c = (Car) cars.getItem(position);
tvCar.setText(c.getCarName());
标签:android,java,model,adapter,custom-adapter
来源: https://codeday.me/bug/20190828/1756701.html