我怎样才能消除从ListView的onItemClick / getView和行类型的依赖? [英] How can I eliminate the dependency from of a ListView's onItemClick/getView and its row types?

查看:199
本文介绍了我怎样才能消除从ListView的onItemClick / getView和行类型的依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个简单的例子,假设有一个的ListView ,可以包含两个子类别和书名。如果点击书名,一个新的活动应该开始显示封面图片。如果点击一个子类,显示的书籍和类别的新列表。

As a simplified example, consider a ListView that can contain both sub-categories and book titles. If a book title is clicked, a new activity should start that shows the cover image. If a sub-category is clicked, a new list of books and categories is displayed.

A 接口定义如下。

A Row interface is defined as follows.

interface Row {
   void onClick();
   void draw(View v);
}

我想知道如何prevent从的ListView ArrayAdapter ,以及依赖从 onItemClickListener 的实施者上的实施者(例如,图书类别)。

I would like to know how to prevent a dependency from the ListView's ArrayAdapter as well as from the implementer of onItemClickListener on the Row implementers (e.g.,Book and Category).

其中的力量推动这个要求就是不要重复自己(DRY)原则: ArrayAdapter 的实现并不需要在新行类型改变出台。

One of the forces driving this requirement is the "don't repeat yourself" (DRY) principle: the ArrayAdapter implementation does not need to change when new row types are introduced.

推荐答案

请原谅我的鸡划伤UML的,但在这里就是我如何做到这一点。

Forgive my chicken-scratched "UML" below, but here's how I do it.

class ListAdapter extends ArrayAdapter<Row<?>> {
...
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = listViewRowViewRecycler.getView(convertView);
        rowProvider.get().getRow(position).draw(view);
        return view;
    }
}

OnItemClickListener 的实施者有一个方法是这样的:

The implementer of OnItemClickListener has a method like this:

void onItemClick(AdapterView<?> adapterView, View view, int rowIndex, long rowId)
{
   rowProvider.onItemClick(rowIndex);
}

然后 RowProvider 有这样的方法:

void onItemClick(int rowIndex) {
    rowList.get(rowIndex).onClick();
}

然后接口与签名无效的onClick(),有类别和图书 提供必要的行为。的实现

Then the Row interface has a method with signature void onClick() and there are Category and Book implementations of Row that provide the necessary behavior.

这篇关于我怎样才能消除从ListView的onItemClick / getView和行类型的依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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