はじめに
時々 、私は外国人の記事を感じる、最近見たか、より深い国の深さよりも思考
RecyclerViewでMVPを使用して記事を、私は特に翻訳され、記録、非常に良い感じ。
原文
MVPでRecyclerView -パッシブビューのアプローチ
翻訳
RecyclerViewを使用して(または他のビューにはアダプタが必要)するたびに、最も重要なことは、データを処理する方法です。
多くの場合、我々は、表示するデータを保存するためにそれを使用し、コレクションアダプタ(例えば、リスト)でコレクションを保持する傾向があります。MVP(モデル-ビュー-プレゼンター)モードでは、我々は一般的にプレゼンター内のデータを保存し、アダプタで開催されたデータは、リストを導くことができる非常に悪い状況は、2つの異なる場所で参照されていますしかし、我々のデータの変更は、我々は2のデータを変更する必要があります。
まず、アダプターは、データを保存し、すべての論理のプレゼンテーションは、タスクのプレゼンターでなければなりませんので、受動的原理とMVPパターンルールの一般的な見解を破るために(関連する要素の追加や更新、削除することで)それを操作することができます。それでは、どのようにこの問題を解決するには?
最初に、それは私たちのアダプターでプレゼンターを必要とするデータを通知することができましょう、各エントリは、ディスプレイ上のMVPとして表示されます。
public class RepositoriesRecyclerAdapter extends RecyclerView.Adapter<ReposRecyclerAdapter.RepoViewHolder> {
private final RepositoriesListPresenter presenter;
public ReposRecyclerAdapter(RepositoriesListPresenter repositoriesPresenter) {
this.presenter = repositoriesPresenter;
}
@Override
public RepositoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RepositoryViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.cell_repo_view, parent, false));
}
@Override
public void onBindViewHolder(RepositoryViewHolder holder, int position) {
presenter.onBindRepositoryRowViewAtPosition(position, holder);
}
@Override
public int getItemCount() {
return presenter.getRepositoriesRowsCount();
}
}
あなたは、私たちのホルダーは、私たちのプレゼンターを通過し、気づいているかもしれません。
あなたはpersenterは、ビュー層に頼ることができない、ろくでなし!あなたは今しっかりpersenterとホルダー一緒に結合されます。
私たちが見て取り、心配しないでRepositoryViewHolderの実装を。
public class RepositoryViewHolder extends RecyclerView.ViewHolder implements RepositoryRowView {
TextView titleTextView;
TextView starsCountTextView;
public RepositoryViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.repoTitleText);
starsCountTextView = itemView.findViewById(R.id.repoStarsCountText);
}
@Override
public void setTitle(String title) {
titleTextView.setText(title);
}
@Override
public void setStarCount(int starCount) {
starsCountTextView.setText(String.format("%s ★", starCount));
}
}
あなたが私たちの見解としてRepositoryViewHolderをあるRepositoryRowViewの表示層における典型的なMVPのインタフェースである特定の実装、。
interface RepositoryRowView {
void setTitle(String title);
void setStarCount(int starCount);
}
インターフェイス、ない実装で呼び出さプレゼンター。
public class RepositoriesListPresenter {
private final List<Repository> repositories;
...
public void onBindRepositoryRowViewAtPosition(int position, RepositoryRowView rowView) {
Repository repo = repositories.get(position);
rowView.setStarCount(repo.getStarsCount());
rowView.setTitle(repo.getTitle());
}
public int getRepositoriesRowsCount() {
return repositories.size();
}
...
}
したがって、データの各行が必要とすべてのロジックとpersentに移し、単純かつ(無知図であるpersenter特定の層のために実装、何アンドロイドフレームを知らない)構造を破壊しません。
まとめ
記事が非常に簡単で、私たちは通常、アダプタは成層、ビジネスロジックとプレゼンテーションより慎重になります使用して隔離されて、私はそれが学習の価値があると感じ、実現するために、良いアイデアです。