有兩個對象:填寫兩個不同的對象到一個單一的ListView
public class Restaurant {
public String name;
public String address;
public int type;
public double duration;
public double lat;
public double lng;
public boolean isStar;
public int contact;
}
public class Spot {
public String name;
public String address;
public int type;
public double duration;
public double lat;
public double lng;
public boolean isStar;
}
我有每個對象的兩個數組列表,我想填充到ListView中,發現的唯一區別他們是餐廳有接觸場。並且適配器是這樣
public class ResultAdapter extends ArrayAdapter<Restaurant> {
public ResultAdapter(Context context, int resource, List<Restaurant> items) {
super(context, resource, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.result_row, null);
}
Restaurant p = (Restaurant) getItem(position);
if (p != null) {
TextView duration = (TextView) v.findViewById(R.id.duration);
TextView name = (TextView) v.findViewById(R.id.name);
TextView address = (TextView) v.findViewById(R.id.address);
TextView type = (TextView) v.findViewById(R.id.type);
TextView contact = (TextView) v.findViewById(R.id.contact);
nameView.setText(p.name);
addressView.setText(p.address);
typeView.setText(p.type == 1 ? "Chinese Cuisine" : "Western Cuisine");
contactView.setText(""+p.contact);
}
return v;
}
}
的問題是我怎麼能在這種情況下創建適配器,因爲適配器是假設提供一個數據類型?我是否需要重新設計結構/創建一個新的Result對象?
更新
public class Restaurant extends Spot{
public String name;
public String address;
public int type;
public double duration;
public double lat;
public double lng;
public boolean isStar;
public int contact;
public Restaurant(String _name, String _address, int _type, double _duration, double _lat, double _lng, boolean _isStar, int _contact) {
name = _name;
address = _address;
type = _type;
duration = _duration;
lat = _lat;
lng = _lng;
isStar = _isStar;
contact = _contact;
}
}
對不起,於二OO軟弱,我怎麼可以改變的構造?
您將所有字段公開,並且您沒有Spot的構造函數。你爲什麼認爲你會需要一個餐廳?你可以像這樣創建你的點:'Spot s = new Spot();'然後分配所有字段。對派生的'Restaurant'使用相同的方法,不需要顯式構造函數。 – kiruwka