万能适配器,鸿洋大神出品:
引入
ForRecyclerView
compile 'com.zhy:base-rvadapter:3.0.3'
ForListView
compile 'com.zhy:base-adapter:3.0.3'
使用方法:
mRecyclerView.setAdapter(new CommonAdapter<String>(this, R.layout.item_list, mDatas)
{
@Override
public void convert(ViewHolder holder, String s)
{
holder.setText(R.id.id_item_list_title, s);
}
});
是不是相当方便,在convert方法中完成数据、事件绑定即可。
只需要简单的将Adapter继承CommonAdapter,复写convert方法即可。省去了自己编写ViewHolder等大量的重复的代码。
多布局的情况下:
MultiItemTypeAdapter adapter = new MultiItemTypeAdapter(this,mDatas);
adapter.addItemViewDelegate(new MsgSendItemDelagate());
adapter.addItemViewDelegate(new MsgComingItemDelagate());
//假装获取数据类型不同
private void getDatas() {
List<Object> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ManEntity manEntity = new ManEntity();
UserEntity userEntity = new UserEntity();
userEntity.setNickName(i+"我的");
manEntity.setDrawable(R.mipmap.de);
manEntity.setNum(i);
manEntity.setStr("出茨木"+i);
list.add(manEntity);
list.add(userEntity);
}
this.lists = list;
}
每种Item类型对应一个ItemViewDelegete,例如:
public class MsggotoItemDelagate implements ItemViewDelegate<Object> {
@Override
public int getItemViewLayoutId() {
return R.layout.recycle_item2;
}
@Override
public boolean isForViewType(Object item, int position) {
return item instanceof UserEntity;
}
@Override
public void convert(ViewHolder holder, Object objects, int position) {
holder.setText(R.id.tv,((UserEntity)objects).getNickName());
}
}
添加HeaderView、FooterView:
mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(mAdapter);
TextView t1 = new TextView(this);
t1.setText("Header 1");
TextView t2 = new TextView(this);
t2.setText("Header 2");
mHeaderAndFooterWrapper.addHeaderView(t1);
mHeaderAndFooterWrapper.addHeaderView(t2);
mRecyclerView.setAdapter(mHeaderAndFooterWrapper);
mHeaderAndFooterWrapper.notifyDataSetChanged();
类似装饰者模式,直接将原本的adapter传入,初始化一个HeaderAndFooterWrapper对象,然后调用相关API添加。
添加LoadMore:
mLoadMoreWrapper = new LoadMoreWrapper(mOriginAdapter);
mLoadMoreWrapper.setLoadMoreView(R.layout.default_loading);
mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener()
{
@Override
public void onLoadMoreRequested()
{
}
});
mRecyclerView.setAdapter(mLoadMoreWrapper);
直接将原本的adapter传入,初始化一个LoadMoreWrapper对象,然后调用相关API即可。
添加EmptyView:
mEmptyWrapper = new EmptyWrapper(mAdapter);
mEmptyWrapper.setEmptyView(R.layout.empty_view);
mRecyclerView.setAdapter(mEmptyWrapper );
直接将原本的adapter传入,初始化一个EmptyWrapper对象,然后调用相关API即可。
支持链式添加多种功能,示例代码:
mAdapter = new EmptyViewWrapper(
new LoadMoreWrapper(
new HeaderAndFooterWrapper(mOriginAdapter)));
附上此适配器Github链接
网友评论