如何消除ListView的onItemClick / getView及其行类型的依赖关系? [英] How can I eliminate the dependency from of a ListView's onItemClick/getView and its row types?
问题描述
作为一个简化的例子,考虑一个可以包含子类别和书籍标题的 ListView
。如果一个书名被点击,一个新的活动应该开始显示封面图像。如果点击了子类别,则会显示新的图书和类别列表。
行
界面是定义如下。
interface Row {
void onClick();
void draw(View v);
}
我想知道如何防止从 ListView
的 ArrayAdapter
以及 onItemClickListener
的实现者行
实现者(例如书
和类别
)。 p>
驱动这个要求的力量之一是不要重复自己(DRY)原则: ArrayAdapter
实现
在下面原谅我的划痕的UML,但这里是如何我这样做
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);
返回视图;
}
}
实现者 OnItemClickListener
有一个这样的方法:
void onItemClick(AdapterView<?> adapterView,View view,int rowIndex,long rowId)
{
rowProvider.onItemClick(rowIndex);
}
然后 RowProvider
一个这样的方法:
void onItemClick(int rowIndex){
rowList.get(rowIndex).onClick() ;
}
然后行
接口有一个方法,具有签名 void onClick()
,还有类别
和 Book
执行
行
,提供必要的行为。
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 Row
interface is defined as follows.
interface Row {
void onClick();
void draw(View v);
}
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
).
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.
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;
}
}
The implementer of OnItemClickListener
has a method like this:
void onItemClick(AdapterView<?> adapterView, View view, int rowIndex, long rowId)
{
rowProvider.onItemClick(rowIndex);
}
Then RowProvider
has a method like this:
void onItemClick(int rowIndex) {
rowList.get(rowIndex).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屋!