为什么 ArrayAdapter 专门用于 TextView?

Why are ArrayAdapters specialized for TextViews?

我正在做一个 Android 项目,我们有许多不同的复合数据类型需要自定义数组适配器。我们必须做一堆样板类型的东西来适应 "generic" 行为,这允许我们发送这些复合数据类型。

我查看了 ArrayAdapter 的实现,发现了这个:

private View createViewFromResource(int position, View convertView, ViewGroup parent,
        int resource) {
    View view;
    TextView text;

    if (convertView == null) {
        view = mInflater.inflate(resource, parent, false);
    } else {
        view = convertView;
    }

    try {
        if (mFieldId == 0) {
            //  If no custom field is assigned, assume the whole resource is a TextView
            text = (TextView) view;
        } else {
            //  Otherwise, find the TextView field within the layout
            text = (TextView) view.findViewById(mFieldId);
        }
    } catch (ClassCastException e) {
        Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
        throw new IllegalStateException(
                "ArrayAdapter requires the resource ID to be a TextView", e);
    }

    T item = getItem(position);
    if (item instanceof CharSequence) {
        text.setText((CharSequence)item);
    } else {
        text.setText(item.toString());
    }

    return view;
}

如您所见,ArrayAdapter class 专门用于创建具有单个 TextView 的视图。在我看来,这似乎是一个相当大的设计缺陷,因为很明显并非所有 ArrayAdapter 都将只处理文本。如果我能够修复它,我会将当前的 ArrayAdapter 实现(处理 TextViews)作为更通用的 ArrayAdapter 的专门化。

我错过了什么吗?为什么做出这个设计决定?是否有一些标准或公认的解决方法?

As you can see, the ArrayAdapter class is geared specifically to creating views with single TextViews.

不,不是。它专门用于处理具有 1+ TextView 个小部件的项目视图,以及可能的其他小部件。

This seems to me a fairly large design flaw since it should have been obvious that not all ArrayAdapters are going to be dealing solely with text.

ArrayAdapter 中没有任何内容将其限制为 "dealing solely with text"。它确实有一个限制,如果您的项目视图有零个 TextView 小部件(或从 TextView 继承的小部件),则您不能使用继承的 getView()。理想情况下,ArrayAdapter 会检查 null 小部件并继续滚动。理想情况下,我会有头发。

其次,在 Android 首次开发时,与十年前相比有点害羞,主要的 ListView 内容 "solely... text".请记住,十年前的设备所使用的 CPU 的功率仅为当今移动设备(例如 66MHz 单核)的百分之几。用户界面根本就没有那么复杂。

If I were able to fix it, I would make the current ArrayAdapter implementation (dealing with TextViews) as a specialization of a more generic ArrayAdapter.

那叫BaseAdapter.

请注意,在 RecyclerView 世界中, 没有 ArrayAdapter 等价物 — 您正在使用更类似于 BaseAdapter 的东西。

Why was this design decision made?

给自己造一台时光机,回到2005-2007年,然后问问Android开发者为什么要这样做。否则,我们将需要以您正在征求意见为由关闭此问题。

Is there some standard or accepted way around this?

或者:

  • 不要链接到继承的getView(),如果它不能满足您的需求(没有TextView,需要多个项目视图布局等),或者

  • 允许 ArrayAdapter 处理一个 TextView,而您处理其余的,或者

  • 使用BaseAdapter你自己的任意集合,或者

  • 使用 BaseAdapter 的其他子类,无论是来自 Android 还是第三方,或者

  • 切换到RecyclerView