一 、前言
1.我们的目标
把RecyclerView下拉刷新上拉加载更多加入到我们的开发者头条APP中。
2.效果图
3.实现步骤
• 找一个带上拉刷新下载加载更多的RecyclerView开源库,我们要站在巨人的肩膀上
• 下载下来自己先运行下demo,然后看看是不是我们需要的功能,觉得不错就把module依赖进来,整合主项目。
• 整合进来了之后,我们肯定需要进行修改,例如我这边就有滑动冲突,有多个headView等问题。
二 、具体实现
1.寻找RecyclerView上拉刷新下载加载开源库
我们找开源项目肯定首选github,去搜索一下一大堆,如果效果图是你想要的功能的话,然后找排名靠前,收藏比较多的项目吧,我找的项目是CommonPullToRefresh,支持ListView,RecyclerView,GridView,SwipeRefreshLayout等常用控件。我跑了一下Demo,没啥bug,挺好用的。
2.加入项目中
1).module导入进来,然后主项目依赖一下。
2).代码实现,我们这边就是修改SelectedFragment
首先我们看布局文件的变化,在RecyclerView外面包裹了自定义的一个类PtrClassicFrameLayout,内部实现了下拉刷新,上拉加载更多。还可以设置自定义属性,都是啥意思我就不解释了,有兴趣的点击github上那个链接,讲解的很详细。
XML/HTML代码
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <com.chanven.lib.cptr.PtrClassicFrameLayout xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
- android:id="@+id/test_recycler_view_frame"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#f0f0f0"
- cube_ptr:ptr_duration_to_close="200"
- cube_ptr:ptr_duration_to_close_header="700"
- cube_ptr:ptr_keep_header_when_refresh="true"
- cube_ptr:ptr_pull_to_fresh="false"
- cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
- cube_ptr:ptr_resistance="1.8">
-
- <android.support.v7.widget.RecyclerView
- android:id="@+id/test_recycler_view"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@android:color/white"/>
- </com.chanven.lib.cptr.PtrClassicFrameLayout>
- </LinearLayout>
再来看onCreateView方法,这个代码就不解释了。
Java代码
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
- View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected, null);
-
- ptrClassicFrameLayout = (PtrClassicFrameLayout) rootView.findViewById(R.id.test_recycler_view_frame);
- mRecyclerView = (RecyclerView) rootView.findViewById(R.id.test_recycler_view);
- mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
-
- init();
- return rootView;
- }
在onCreateView里面调用了init()方法,我们来瞧瞧怎么实现的。这里解释一下为什么要对适配器进行包装,这样的目的在包装类里面处加入头部,底部View,处理点击事件。大家拿到源码了之后自己也可以看看。
Java代码
- private void init() {
-
- selectedAdapter = new SelectedRecyclerAdapter(getActivity());
-
- mAdapter = new RecyclerAdapterWithHF(selectedAdapter);
-
- mAdapter.addCarouse(initCarouselHead());
- mRecyclerView.setAdapter(mAdapter);
- ptrClassicFrameLayout.setPtrHandler(ptrDefaultHandler);
- ptrClassicFrameLayout.setOnLoadMoreListener(onLoadMoreListener);
- ptrClassicFrameLayout.setLoadMoreEnable(true);
- }
mAdapter.addCarouse(initCarouselHead()); 初始化一个滚动Banner,然后加入适配器头部。这个我前面的教程应该已经讲过了。。
Java代码
-
- private View initCarouselHead(){
- View headView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected_header,mRecyclerView,false);
-
- tvContent=(TextView) headView.findViewById(R.id.tv_content);
- tvContent.setText(carousePageStr[0]);
-
- viewPager = (ViewPager)headView.findViewById(R.id.viewpager);
- selectedPagerAdapter=new SelectedPagerAdapter(getActivity(),carousePagerSelectView);
- viewPager.setOffscreenPageLimit(2);
- viewPager.setCurrentItem(0);
- viewPager.addOnPageChangeListener(onPageChangeListener);
- viewPager.setAdapter(selectedPagerAdapter);
-
- ViewGroup group = (ViewGroup) headView.findViewById(R.id.viewGroup);
- tips = new ImageView[3];
- for (int i = 0; i < tips.length; i++){
- ImageView imageView = new ImageView(getActivity());
- if (i == 0) {
- imageView.setBackgroundResource(R.mipmap.page_indicator_focused);
- } else {
- imageView.setBackgroundResource(R.mipmap.page_indicator_unfocused);
- }
-
- tips[i] = imageView;
- LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
- layoutParams.leftMargin = 10;
- layoutParams.rightMargin = 10;
- group.addView(imageView, layoutParams);
- }
-
- timer = new Timer(true);
- timer.schedule(task, 0, CAROUSEL_TIME);
-
- return headView;
- }
SelectedRecyclerAdapter 必须继承RecyclerView.Adapter
这玩意跟ListView的适配器差不多,用过ListView适配器的应该一看就懂了。
首先会调用getItemCount,知道我要显示多少item。
知道了行数然后就是循环调用onCreateViewHolder跟onBindViewHolder了,onCreateViewHolder就是创建一个item的View,onBindViewHolder就会把上次创建的item的View传入进来,还有一个下标,这样我们就能给每一行赋值,这两个方法都是先后一起调用。item回收重用的机制应该跟ListView一样的。
Java代码
- public class SelectedRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
- private List<SelectedArticle> selectedArticles;
- private LayoutInflater inflater;
-
- public SelectedRecyclerAdapter(Context context) {
- super();
- inflater = LayoutInflater.from(context);
-
- selectedArticles = new ArrayList<SelectedArticle>();
- initData();
- }
-
- private void initData() {
- for (int i = 0; i < 10; i++) {
- SelectedArticle selectedArticle = new SelectedArticle(i, "Android开发666", i, i, "");
- selectedArticles.add(selectedArticle);
- }
- }
-
- public void loadMore(int page) {
- for (int i = 0; i < 5; i++) {
- SelectedArticle selectedArticle = new SelectedArticle(i, "第" + page + "页数据", i, i, "");
- selectedArticles.add(selectedArticle);
- }
- }
-
- public void getFirst() {
- selectedArticles.clear();
- initData();
- }
-
- @Override
- public int getItemCount() {
- return selectedArticles.size();
- }
-
- @Override
- public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
- SelectedRecyclerHolder holder = (SelectedRecyclerHolder) viewHolder;
-
- SelectedArticle selectedArticle = selectedArticles.get(position);
- holder.title.setText(selectedArticle.getTitle());
- holder.like.setText("" + selectedArticle.getLikeNumber());
- holder.comment.setText("" + selectedArticle.getCommentNumber());
- }
-
- @Override
- public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewHolder, int position) {
- View view = inflater.inflate(R.layout.fragment_selected_item, null);
- return new SelectedRecyclerHolder(view);
- }
-
- public class SelectedRecyclerHolder extends RecyclerView.ViewHolder {
- private TextView title;
- private TextView like;
- private TextView comment;评论数量
-
- public SelectedRecyclerHolder(View view) {
- super(view);
- title = (TextView) view.findViewById(R.id.tv_title);
- like = (TextView) view.findViewById(R.id.tv_like);
- comment = (TextView) view.findViewById(R.id.tv_comment);
- }
- }
- }
3.解决整合进来的bug
• 滑动冲突
当我们上拉到顶部把标题栏挤出屏幕外的时候,进行下拉会触发RecyclerView的下拉事件,正确的情况应该是显示Toolbar.
1).RecyclerView下拉刷新的时候先判断Toolbar有没有显示。如果Toolbar没有显示就不处理。
2).AppBarLayout有一个addOnOffsetChangedListener方法,在AppBarLayout的布局偏移量发生改变时被调用。
在MainFragment里面进行监听
Java代码
- appBarLayout= (AppBarLayout) rootView.findViewById(R.id.appBarLayout);
- appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
然后在回调函数中,把值给SelectedFragment,
Java代码
- private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener=new AppBarLayout.OnOffsetChangedListener() {
- @Override
- public void onOffsetChanged(AppBarLayout appBarLayout, int i){
-
- selectedFragment.setPullRefresh(i>=0);
- System.out.println("i值:"+i);
- }
- };
3).在SelectedFragment中,继续把值传给PtrFrameLayout
Java代码
- public void setPullRefresh(boolean pullRefresh) {
- ptrClassicFrameLayout.setPullRefresh(pullRefresh);
- }
4.在PtrFrameLayout里面用一个实例变量接收这个值
Java代码
- private boolean pullRefresh=true;
-
- public void setPullRefresh(boolean pullRefresh) {
- this.pullRefresh = pullRefresh;
- }
4).找到PtrFrameLayout类的dispatchTouchEvent事件,这个方法是处理屏幕的触摸事件的。
Java代码
- @Override
- public boolean dispatchTouchEvent(MotionEvent e) {
- if (!isEnabled() || mContent == null || mHeaderView == null) {
- System.out.println("都是空的...");
- return dispatchTouchEventSupper(e);
- }
- int action = e.getAction();
- switch (action) {
- case MotionEvent.ACTION_UP:
- System.out.println("弹起...");
- case MotionEvent.ACTION_CANCEL:
- System.out.println("取消...");
-
- mPtrIndicator.onRelease();
- if (mPtrIndicator.hasLeftStartPosition()) {
- if (DEBUG) {
- PtrCLog.d(LOG_TAG, "call onRelease when user release");
- }
- System.out.println("call onRelease when user release");
- onRelease(false);
- if (mPtrIndicator.hasMovedAfterPressedDown()) {
- sendCancelEvent();
- return true;
- }
- }
- return dispatchTouchEventSupper(e);
-
- case MotionEvent.ACTION_DOWN:
- System.out.println("按下...");
- mHasSendCancelEvent = false;
- mPtrIndicator.onPressDown(e.getX(), e.getY());
-
- mScrollChecker.abortIfWorking();
-
- mPreventForHorizontal = false;
-
-
-
- return dispatchTouchEventSupper(e);
- case MotionEvent.ACTION_MOVE:
- System.out.println("移动...");
- if(pullRefresh){
- mLastMoveEvent = e;
- mPtrIndicator.onMove(e.getX(), e.getY());
- float offsetX = mPtrIndicator.getOffsetX();
- float offsetY = mPtrIndicator.getOffsetY();
-
- if (mDisableWhenHorizontalMove && !mPreventForHorizontal && (Math.abs(offsetX) > mPagingTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) {
- if (mPtrIndicator.isInStartPosition()) {
- mPreventForHorizontal = true;
- }
- }
- if (mPreventForHorizontal) {
- return dispatchTouchEventSupper(e);
- }
-
- boolean moveDown = offsetY > 0;
- boolean moveUp = !moveDown;
- boolean canMoveUp = mPtrIndicator.hasLeftStartPosition();
-
- if (DEBUG) {
- boolean canMoveDown = mPtrHandler != null && mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView);
- PtrCLog.v(LOG_TAG, "ACTION_MOVE: offsetY:%s, currentPos: %s, moveUp: %s, canMoveUp: %s, moveDown: %s: canMoveDown: %s", offsetY, mPtrIndicator.getCurrentPosY(), moveUp, canMoveUp, moveDown, canMoveDown);
- }
-
-
- if (moveDown && mPtrHandler != null && !mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView)) {
- return dispatchTouchEventSupper(e);
- }
-
- if ((moveUp && canMoveUp) || moveDown) {
-
- movePos(offsetY);
- return true;
- }
- }
- }
- return dispatchTouchEventSupper(e);
- }
我就改了一行代码,在action==MotionEvent.ACTION_MOVE的时候,先判断我们传入的pullRefresh是否为true。。。
• 顶部加入轮播
RecyclerView头部底部加入View,前面我们介绍过了,都是适配器的封装类RecyclerAdapterWithHF来控制。从效果图中,我们可以看出,轮播的View是加入头部的,找到RecyclerAdapterWithHF类,看看源码依葫芦画瓢就可以了。
1).得有一个保存View的集合,其实用一个变量也行,因为我们只有一个轮播View.
Java代码
- private List<View> mCarouse = new ArrayList<View>();
-
- public void addCarouse(View view){
- mCarouse.add(view);
- }
2).定义一个常量,用于类型判断
Java代码
- public static final int TYPE_CAROUSE = 7900;
3).在getItemViewType里面加入轮播的类型
Java代码
- @Override
- public final int getItemViewType(int position) {
-
-
- if (isHeader(position)) {
- return TYPE_HEADER;
-
- } else if (mCarouse.size()>0&&mHeaders.size()==position){
- return TYPE_CAROUSE;
- }else if (isFooter(position)) {
- return TYPE_FOOTER;
- }
- int type = getItemViewTypeHF(getRealPosition(position));
- if (type == TYPE_HEADER || type == TYPE_FOOTER|| type == TYPE_CAROUSE) {
- throw new IllegalArgumentException("Item type cannot equal " + TYPE_HEADER + " or " + TYPE_FOOTER);
- }
- return type;
- }
4).onCreateViewHolder里面也要修改一下,就是在if里面多加了个&&.无论是头部,底部,轮播的View,都是添加到FrameLayout里面的。
Java代码
- @Override
- public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
-
-
- if (type != TYPE_HEADER && type != TYPE_FOOTER && type != TYPE_CAROUSE) {
- ViewHolder vh = onCreateViewHolderHF(viewGroup, type);
- return vh;
-
- } else {
-
- FrameLayout frameLayout = new FrameLayout(viewGroup.getContext());
-
- frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
- return new HeaderFooterViewHolder(frameLayout);
- }
- }
5).onBindViewHolder这里为item绑定数据,其实就是第四步返回的ItemView绑定数据.
Java代码
- @Override
- public final void onBindViewHolder(final RecyclerView.ViewHolder vh, int position){
-
- if (isHeader(position)) {
- View v = mHeaders.get(position);
-
- prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
- }else if(mCarouse.size()>0&&position==mHeaders.size()){
-
- View v = mCarouse.get(mHeaders.size());
- prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
- } else if (isFooter(position)) {
- View v = mFooters.get(position - getItemCountHF() - mHeaders.size());
-
- prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
- } else {
- vh.itemView.setOnClickListener(new MyOnClickListener(vh));
- vh.itemView.setOnLongClickListener(new MyOnLongClickListener(vh));
-
- onBindViewHolderHF(vh, getRealPosition(position));
- }
- }
6).我们从第五步看到头部底部轮播View最后都会调用prepareHeaderFooter方法。看到这方法的源码,其实就是把类型对应的View,添加到Item中.
Java代码
- private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view) {
-
- if (mManagerType == TYPE_MANAGER_STAGGERED_GRID) {
- StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams
- (ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
- layoutParams.setFullSpan(true);
- vh.itemView.setLayoutParams(layoutParams);
- }
-
-
- if (view.getParent() != null) {
- ((ViewGroup) view.getParent()).removeView(view);
- }
-
-
- vh.base.removeAllViews();
- vh.base.addView(view);
- }
三、源码下载
源码下载