Reputation: 543
The solution is in the bottom:
I made some classes that i want to use in a listview. They look like this:
public class Equipment{
....code....
}
and
public class Weapon extends Equipment{
...More code...
}
and
public class Armor extends Equipment{
...More code...
}
As you can see weapon and armor extends equipment. Now i want to use theese classes in the same ArrayAdapter. In my imagination it would be simple as this:
public class ShopItemAdapter extends ArrayAdapter<Equipment>{
private List<Equipment> itemList;
public ShopItemAdapter(Context context, List<Equipment> itemList) {
super(context, android.R.layout.simple_list_item_1, itemList);
this.itemList = itemList;
this.context = context;
}
.... CODE ....
}
But for some reason I may not create an ArrayAdapter Equipment with List Weapon or List Armor.
ShopItemAdapter adapter = new ShopItemAdapter(getApplicationContext(), weaponList);
This codes gives me the error that ShopItemAdapter(Context, List) is undefined
Am I using subclasses in the wrong way or what?
My goal is to show a list of armors when clicking on a button and viseversa.
Hope my problem is clear. Thanks!
SOLUTION ** So i just needed to change the constructor to receive then cast to List in the super constructor.
public class ShopItemAdapter extends ArrayAdapter<Equipment>{
private List<Equipment> itemList;
public ShopItemAdapter(Context context, List<? extends Equipment> itemList) {
super(context, android.R.layout.simple_list_item_1, (List<Equipment>)itemList);
this.itemList = (List<Equipment>)itemList;
this.context = context;
}
.... CODE ....
}
Upvotes: 1
Views: 791
Reputation: 152927
When creating an adapter i get the error "The constructor ShopItemAdapter(Context, List) is undefined. Do need to create a constructor for every List types? Seems weird as Weapon extends Equipment. :(
No, but you need to specify that any subclass of Equipment
will also do:
public ShopItemAdapter(Context context, List<? extends Equipment> itemList) {
?
is a wildcard in Java generics and ? extends A
makes it bound to type A
or its subclasses.
Upvotes: 1
Reputation: 9794
Your idea is fine, but you will also have to override getView() and populate your layout there. The default is for ArrayAdapter to populate a single TextView.
Upvotes: 0