转载请注明出处:http://blog.csdn.net/xiaoyuan511
一、概述
我们在写项目的时候,永远都离不开ListView、RecyclerView这类的控件,几乎是在任何的APP中都可以看到他们的影子,但是RecyclerView并没有像ListView提供了addHeadView、addFooterView这样的原生方法,更没有提供onItemclicklistener这样的方法,所有这样方法需要我们自己手动实现。在这里吐槽一个谷歌。不知道谷歌是怎么想的。
下拉刷新跟加载更多更是我们随处可以见的。但是有些App要上拉一下才能加载更多,我觉得让用户多了一步这样的操作,感觉完全是没有必要的,用户体验并不好。如果不自动加载更多是因为用户的流量,我就这种担心完全是没有必要的。所以我认为上拉加载更多这样的功能是非常鸡肋的,滑到底部正常就应该自动加载更多。
二、原理
既然谷歌没有为RecyclerView 没有提供这样方法,那我们只能自己手动实现了。
根据item_type类型不同来实现给RecyclerView加头部的效果
判断是否滑动到最后一条来实现加载更多,其实也是根据item_type不同来实现
下拉刷新谷歌有原生的swiperefreshlayout
三、效果图
加载更多有三中情况
加载中、加载完成
加载失败、点击重试
加载完成并没有更多数据了
四、代码
public abstract class BaseAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int TYPE_FOOTER_VIEW = 100002;//footer类型 Item
protected Context mContext;
private OnLoadMoreListener mLoadMoreListener;//加载更多回调
private View mLoadingView; //加载中
private View mLoadFailedView; //加载失败
private View mLoadEndView; //加载完成
private RelativeLayout mFooterLayout;//加载布局
protected List<T> mDatas;//数据源
private boolean mOpenLoadMore;//是否开启加载更多
private boolean isAutoLoadMore = true;//是否自动加载,当数据不满一屏幕会自动加载
private boolean isAddHead;//是否根据Item type添加头
protected abstract int getViewType(int position, T data);
public BaseAdapter(Context context, List<T> datas, boolean isOpenLoadMore) {
mContext = context;
mDatas = datas == null ? new ArrayList<T>() : datas;
mOpenLoadMore = isOpenLoadMore;
}
@Override
public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CommonViewHolder viewHolder = null;
switch (viewType) {
case TYPE_FOOTER_VIEW:
if (mFooterLayout == null) {
mFooterLayout = new RelativeLayout(mContext);
}
viewHolder = CommonViewHolder.create(mFooterLayout);
break;
}
return viewHolder;
}
@Override
public int getItemCount() {
if (mDatas.isEmpty()) {
return 0;
}
return mDatas.size() + getFooterViewCount();
}
@Override
public int getItemViewType(int position) {
if (isFooterView(position)) {
return TYPE_FOOTER_VIEW;
}
return getViewType(position, mDatas.get(position));
}
/**
* 根据positiond得到data
*
* @param position
* @return
*/
public T getItem(int position) {
if (mDatas.isEmpty()) {
return null;
}
return mDatas.get(position);
}
/**
* 是否是FooterView
*
* @param position
* @return
*/
private boolean isFooterView(int position) {
return mOpenLoadMore && position >= getItemCount() - 1;
}
protected boolean isCommonItemView(int viewType) {
return viewType != TYPE_FOOTER_VIEW;
}
/**
* StaggeredGridLayoutManager模式时,FooterView可占据一行
*
* @param holder
*/
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
if (isFooterView(holder.getLayoutPosition())) {
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
p.setFullSpan(true);
}
}
}
/**
* GridLayoutManager模式时, FooterView可占据一行,判断RecyclerView是否到达底部
*
* @param recyclerView
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) layoutManager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (isFooterView(position)) {
return gridManager.getSpanCount();
}
return 1;
}
});
}
startLoadMore(recyclerView, layoutManager);
}
/**
* 判断列表是否滑动到底部
*
* @param recyclerView
* @param layoutManager
*/
private void startLoadMore(RecyclerView recyclerView, final RecyclerView.LayoutManager layoutManager) {
if (!mOpenLoadMore || mLoadMoreListener == null) {
return;
}
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (!isAutoLoadMore && findLastVisibleItemPosition(layoutManager) + 1 == getItemCount()) {
scrollLoadMore();
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (isAutoLoadMore && findLastVisibleItemPosition(layoutManager) + 1 == getItemCount()) {
scrollLoadMore();
} else if (isAutoLoadMore) {
isAutoLoadMore = false;
}
}
});
}
/**
* 到达底部开始加载更多
*/
private void scrollLoadMore() {
if (mFooterLayout.getChildAt(0) == mLoadingView) {
if (mLoadMoreListener != null) {
mLoadMoreListener.onLoadMore(false);
}
}
}
private int findLastVisibleItemPosition(RecyclerView.LayoutManager layoutManager) {
if (layoutManager instanceof LinearLayoutManager) {
return ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(null);
return Util.findMax(lastVisibleItemPositions);
}
return -1;
}
/**
* 清空footer view
*/
private void removeFooterView() {
mFooterLayout.removeAllViews();
}
/**
* 添加新的footer view
*
* @param footerView
*/
private void addFooterView(View footerView) {
if (footerView == null) {
return;
}
if (mFooterLayout == null) {
mFooterLayout = new RelativeLayout(mContext);
}
removeFooterView();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mFooterLayout.addView(footerView, params);
}
/**
* 加载更多的数据
*
* @param datas
*/
public void setLoadMoreData(List<T> datas) {
int size = mDatas.size();
mDatas.addAll(datas);
notifyItemInserted(size);
}
/**
* 下拉刷新
*
* @param datas
*/
public void setData(List<T> datas) {
mDatas.addAll(0, datas);
notifyDataSetChanged();
}
/**
* 初始化数据源
*
* @param datas
*/
public void setInitData(List<T> datas) {
mDatas.clear();
if (isAddHead) {
mDatas.add(null);//让数据源第一条为null来添加头部
}
mDatas.addAll(datas);
notifyDataSetChanged();
}
public void remove(int position) {
mDatas.remove(position);
notifyDataSetChanged();
}
/**
* 是否跟添加头部
*
* @param b
*/
public void setAddHaed(boolean b) {
isAddHead = b;
}
/**
* 初始化加载中布局
*
* @param loadingView
*/
public void setLoadingView(View loadingView) {
mLoadingView = loadingView;
addFooterView(mLoadingView);
}
public void setLoadingView(int loadingId) {
setLoadingView(Util.inflate(mContext, loadingId));
}
/**
* 初始化加载失败布局
*
* @param loadFailedView
*/
public void setLoadFailedView(View loadFailedView) {
if (loadFailedView == null) {
return;
}
mLoadFailedView = loadFailedView;
addFooterView(mLoadFailedView);
mLoadFailedView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addFooterView(mLoadingView);
if (mLoadMoreListener != null) {
mLoadMoreListener.onLoadMore(true);
}
}
});
}
public void setLoadFailedView(int loadFailedId) {
setLoadFailedView(Util.inflate(mContext, loadFailedId));
}
/**
* 初始化加载完成布局
*
* @param loadEndView
*/
public void setLoadEndView(View loadEndView) {
mLoadEndView = loadEndView;
addFooterView(mLoadEndView);
}
public void setLoadEndView(int loadEndId) {
setLoadEndView(Util.inflate(mContext, loadEndId));
}
/**
* 返回foot数量
*
* @return
*/
public int getFooterViewCount() {
return mOpenLoadMore && !mDatas.isEmpty() ? 1 : 0;
}
public void setOnLoadMoreListener(OnLoadMoreListener loadMoreListener) {
mLoadMoreListener = loadMoreListener;
}
}
我们封装一个BaseAdapter,里面主要处理了一些判断是否滑动底部,添加脚、添加头等操作,代码注释的很清楚,大家读一下就知道哪个方法是干什么的了
public class LoadMoreAdapter extends MultiTypeBaseAdapter<String> {
public LoadMoreAdapter(Context context, List<String> datas, boolean isOpenLoadMore) {
super(context, datas, isOpenLoadMore);
}
@Override
protected void convert(CommonViewHolder holder, final String data, int viewType) {
if (viewType == 0) {
} else {
holder.setText(R.id.text1, data);
}
}
@Override
protected int getItemLayoutId(int viewType) {
if (viewType == 0) {
return R.layout.item_head;
}
return R.layout.item_layout1;
}
@Override
protected int getViewType(int position, String data) {
if (data == null) {
return 0;
} else {
return 1;
}
}
}
这个是LoadMoreAdapter,里面根据item_type来判断是否要加载哪个布局,一个是加载头部的布局、一个是加载正常布局。
public class MainActivity extends AppCompatActivity {
private LoadMoreAdapter mAdapter;
private RecyclerView mRecyclerView;
private boolean isFailed = true;
private SwipeRefreshLayout mSwipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe);
mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
//初始化adapter
mAdapter = new LoadMoreAdapter(this, null, true);
mAdapter.setAddHaed(true);//设置有头部
//点击事件
mAdapter.setOnMultiTypeItemClickListener(new OnMultiTypeItemClickListeners<String>() {
@Override
public void onItemClick(CommonViewHolder viewHolder, String data, int position, int viewType) {
if(data == null){
Toast.makeText(MainActivity.this, "我是头部", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
}
});
//刷新数据监听
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadData();
}
});
//加载更多事件
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(boolean isReload) {
loadMore();
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
loadData();//初始化数据
}
/**
* 初始化数据
*/
private void loadData() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
List<String> data = new ArrayList<>();
for (int i = 0; i < 12; i++) {
data.add(i+"");
}
//刷新数据
mAdapter.setInitData(data);
mSwipeRefreshLayout.setRefreshing(false);
mAdapter.setLoadingView(R.layout.load_loading);
}
}, 2000);
}
private void loadMore() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (mAdapter.getItemCount() > 30 && isFailed) {
isFailed = false;
//加载失败
mAdapter.setLoadFailedView(R.layout.load_failed);
} else if (mAdapter.getItemCount() > 50) {
//加载完成
mAdapter.setLoadEndView(R.layout.load_end);
} else {
final List<String> data = new ArrayList<>();
for (int i = 0; i < 12; i++) {
data.add("我是加载更多" + i);
}
mAdapter.setLoadMoreData(data);
}
}
}, 3000);
}
}
这个是Activity里面的代码,里面有下拉刷新,加载更多的逻辑 。大概就这样子,就可以实现下拉刷新,自动加载更多、添加头部功能。
五、源码
六、欢迎大家访问我的网站和我的公众号
极客导航---程序员自己的导航网站
程序员自己的导航网站