简体   繁体   中英

Array adapter with custom subclass objects

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 ....
}

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 ? extends A makes it bound to type A or its subclasses.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM