場景
面對多型別的列表,應該怎麼處理?
解決方案(設計思想的方法--委託者模式)
什麼是委託者模式,簡單的來說就是業務所需要實現的邏輯交給一個目標實現類來完成。 不管任何條目,都統一實現IDelegateAdapter介面
然後讓一個實現類去完成下面是程式碼實現
public interface IDelegateAdapter {
// 查詢委託時呼叫的方法,返回自己能處理的型別即可。
boolean isForViewType(BaseRvBean baseRvBean);
// 用於委託Adapter的onCreateViewHolder方法
SuperViewHolder onCreateViewHolder(ViewGroup parent, int viewType);
// 用於委託Adapter的onBindViewHolder方法
void onBindViewHolder(RecyclerView.ViewHolder holder, int position, BaseRvBean baseRvBean);
//清除資料
void clearData();
}
複製程式碼
由於篇幅原因,程式碼沒有全部貼入
public class BaseRvAdapter extends RecyclerView.Adapter<SuperViewHolder> {
List<IDelegateAdapter> delegateAdapters = new ArrayList<>();
public void addDelegate(IDelegateAdapter delegateAdapter) {
delegateAdapters.add(delegateAdapter);
}
@Override
public SuperViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
IDelegateAdapter iDelegateAdapter = delegateAdapters.get(viewType);
return iDelegateAdapter.onCreateViewHolder(parent, viewType);
}
@Override
public void onBindViewHolder(SuperViewHolder holder, int position) {
int itemViewType = holder.getItemViewType();
IDelegateAdapter iDelegateAdapter = delegateAdapters.get(itemViewType);
iDelegateAdapter.onBindViewHolder(holder, position, mDataList.get(position));
}
@Override
public int getItemViewType(int position) {
BaseRvBean baseRvBean = mDataList.get(position);
for (IDelegateAdapter delegateAdapter : delegateAdapters) {
if (delegateAdapter.isForViewType(baseRvBean)) {
return delegateAdapters.indexOf(delegateAdapter);
}
}
throw new RuntimeException("沒有可以處理的委託Adapter");
}
public void clear() {
mDataList.clear();
for (IDelegateAdapter delegateAdapter : delegateAdapters) {
delegateAdapter.clearData();
}
notifyDataSetChanged();
}
}
複製程式碼
使用方法
- 實現自己業務需要的item型別
class EditTextAdapter : IDelegateAdapter {
override fun clearData() {
mTextCache.clear()
}
override fun isForViewType(baseRvBean: BaseRvBean?): Boolean {
return baseRvBean?.type == ViewType.ITEM_TYPE_GENERAL_EDITTEXT
}
@SuppressLint("InflateParams")
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): SuperViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.view_custom_ed, null)
return ViewHolder(view)
}
private val mTextCache = SparseArray<String>()
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int, baseRvBean: BaseRvBean?) {
}
複製程式碼
- 建立Adapter
mAdapter = BaseRvAdapter(mActivity).apply {
addDelegate(EditTextAdapter())
}
複製程式碼
- 賦值
mAdapter?.setDataList(mDataList )\\這些都是基本操作,大家都會的
複製程式碼
委託模式是不是很簡單呀,把設計模式運用到開發中,真的是件很有意思的事情,大家都可以多嘗試下