安卓:自定义ArrayAdapter(S)为不同的自定义对象 [英] Android: Custom ArrayAdapter(s) for different custom objects

查看:142
本文介绍了安卓:自定义ArrayAdapter(S)为不同的自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,彼此显著不同的自定义对象。这些对象存储在不同的列表,并且将要显示在不同列表视图。因为这些列表视图的设计,我需要创建自己的自定义ArrayAdapter。关键是,ListView的设计应该是对所有列表视图相同的,无论在列表中的对象。

I have a number of custom objects that are significantly different from each other. These objects are stored in different lists and are to be displayed in different ListViews. Because of the design of these ListViews, I need to create my own custom ArrayAdapter. The thing is, the ListView design is supposed to be the same for all ListViews regardless of the objects in the list.

要做到这一点,我创建每种类型对象的ArrayAdapter。例如。自定义对象辅酶我做了ArrayAdapter coAAdapter,以及自定义对象COB我做了ArrayAdapter coBAdapter。这似乎是很不必要的我,因为旁边这些适配器除了什么样的ArrayAdapter的自定义适配器和扩展它们的构造没有区别有:

To accomplish this I created an ArrayAdapter for every type of object. E.g. for a custom object coA I made an ArrayAdapter coAAdapter, and for custom object coB I made an ArrayAdapter coBAdapter. This seems very unnecessary to me, since there are next to no difference between these adapters except what kind of ArrayAdapter the custom adapters extends and their constructors:

适配器类辅酶A:

public class CoAAdapter extends ArrayAdapter<CoA> {
     public CoAAdapter (Context context, int resource, List<CoA> objects) {...}
}

适配器类的CoB:

Adapter for class CoB:

public class CoBAdapter extends ArrayAdapter<CoB> {
     public CoBAdapter (Context context, int resource, List<CoB> objects) {...}
}

这是ArrayAdapters如何自定义应该是使用,还是有一种方法,使这个设计简单了很多,就像所有的自定义对象一个自定义ArrayAdapter?

Is this how custom ArrayAdapters are supposed to be used, or is there a way to make this design a lot simpler, like having one custom ArrayAdapter for all custom objects?

我曾经想过一些不同的解决方案,如创建一个通用的自定义适配器或使用继承由我的自定义对象创建一个共同的基类,但经过一番研究所有这些似乎是一个不错的办法。

I have thought about some different solutions, like creating a generic custom adapter or using inheritance by creating a common base class for my custom objects, but after some research none of these seems like a good approach.

推荐答案

您可以这样定义你的适配器:

You can define your adapter like this:

 public class MyArrayAdapter<T> extends ArrayAdapter<T> 
 {
      HashMap<T, Integer> mIdMap = new HashMap<T, Integer>();

      public MyArrayAdapter(Context context, int textViewResourceId, List<T> objects) {
        super(context, textViewResourceId, objects);
        for (int i = 0; i < objects.size(); ++i) {
          mIdMap.put(objects.get(i), i);
        }
      }
  }

这篇关于安卓:自定义ArrayAdapter(S)为不同的自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆