RecyclerView实现底部加载更多功能

     这两天在公司没有什么任务分配,就研究了下咱们Google在Android5.0 推出的一个用来代替ListView的列表控件----RecyclerView。发现功能上确实比ListView强大了不少,可扩展性也增强了不少。但是使用过RecyclerView的Programmers应该都知道,RecyclerView无法直接代码添加头布局和脚布局。那么他喵的怎么样实现最常用的底部加载更多数据呢?带着这样的疑惑我在StackOverFlow上搜索到了一个有参考价值的答案并写了一个Demo实现了它。参考链接附上:http://stackoverflow.com/questions/30681905/adding-items-to-endless-scroll-recyclerview-with-progressbar-at-bottom?answertab=active#tab-top  

废话不多说,开始进入正题,直接上代码!

第一步:创建两个接口

public interface LoadMoreDataListener {
    public abstract void loadMoreData();
}
public interface RecyclerOnItemClickListener {
    public abstract void onClick(View view);
}
 
  

第二步:根据XML中的布局来创建一个Activity

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private TextView tv_empty;
    private List list = new ArrayList<>();
    private List moreData = new ArrayList<>();
    private List refreshData = new ArrayList<>();
    private MyAdapter myAdapter;
    private Handler handler = new Handler();
    private SwipeRefreshLayout sfl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 TODO: 点击FAB后的操作
            }
        });

        init();
    }

    private void init() {
        initData();
        initRefreshData();
        initMoreData();
        initView();
        initListener();
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        tv_empty = (TextView) findViewById(R.id.tv_empty);
        sfl = (SwipeRefreshLayout) findViewById(R.id.sfl);
        sfl.setColorSchemeColors(Color.parseColor("#FF4081"));
        //创建一个LinearLayoutManager对象
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        //创建adapter对象
        myAdapter = new MyAdapter(this, mRecyclerView);
        mRecyclerView.setAdapter(myAdapter);
        myAdapter.setData(list);//设置数据


        if (list.isEmpty()) {
            mRecyclerView.setVisibility(View.GONE);
            tv_empty.setVisibility(View.VISIBLE);
        } else {
            mRecyclerView.setVisibility(View.VISIBLE);
            tv_empty.setVisibility(View.GONE);
        }

    }

    //初始化数据
    private void initData() {
        for (int i = 0; i < 20; i++) {
            list.add("handsome is wrong?" + i);
        }
    }

    //初始化加载更多数据
    private void initMoreData() {
        for (int i = 0; i < 10; i++) {
            moreData.add("life is good" + i);
        }
    }

    private void initRefreshData() {
        for (int i = 0; i < 2; i++) {
            refreshData.add("refreshData" + i);
        }
    }


    //初始化监听
    private void initListener() {
        sfl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //模拟下拉刷新数据操作
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        list.addAll(0, refreshData);
                        myAdapter.notifyDataSetChanged();
                        sfl.setRefreshing(false);
                    }
                }, 1000);
            }
        });

        //加载更多回调监听
        myAdapter.setOnMoreDataLoadListener(new LoadMoreDataListener() {
            @Override
            public void loadMoreData() {
                //加入null值此时adapter会判断item的type
                list.add(null);
                myAdapter.notifyDataSetChanged();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //移除刷新的progressBar
                        list.remove(list.size() - 1);
                        myAdapter.notifyDataSetChanged();
                        list.addAll(moreData);
                        myAdapter.notifyDataSetChanged();
                        myAdapter.setLoaded();
                    }
                }, 2000);

            }
        });

        myAdapter.setOnItemClickListener(new RecyclerOnItemClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(MainActivity.this, "能不能不要这么帅", Toast.LENGTH_SHORT).show();
                Snackbar.make(view, "Iam BadGuy_Leo", Snackbar.LENGTH_SHORT).show();
            }
        });
    }


}

 

activity_main




    

        

    

    

    


content_main




    

        

        
    

    




创建RecyclerView的条目布局 item_view





    

        

    


创建脚布局item_footer




    


第三步:创建一个RecyclerView的Adapter 这一步是非常关键的一步,使用过RecyclerView的programmer应该都知道它无法设置条目点击事件——!所以必须自己写一个接口回调,来自己定制点击事件。代码如下

/**
 * Author: lihongxiang
 * Time: 上午 11:14
 * Email:[email protected]
 */

public class MyAdapter extends RecyclerView.Adapter {

    private static final int VIEW_ITEM = 0;
    private static final int VIEW_PROG = 1;
    private final Context mContext;
    private final RecyclerView mRecyclerView;
    private List mData;
    private final LayoutInflater inflater;
    private boolean isLoading;
    private int totalItemCount;
    private int lastVisibleItemPosition;
    //当前滚动的position下面最小的items的临界值
    private int visibleThreshold = 5;


    public MyAdapter(Context context, RecyclerView recyclerView) {
        mContext = context;
        inflater = LayoutInflater.from(context);
        mRecyclerView = recyclerView;
        if (mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            //mRecyclerView添加滑动事件监听
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                    Log.d("test", "totalItemCount =" + totalItemCount + "-----" + "lastVisibleItemPosition =" + lastVisibleItemPosition);
                    if (!isLoading && totalItemCount <= (lastVisibleItemPosition + visibleThreshold)) {
                        //此时是刷新状态
                        if (mMoreDataListener != null)
                            mMoreDataListener.loadMoreData();
                        isLoading = true;
                    }
                }
            });
        }

    }

    public void setLoaded() {
        isLoading = false;
    }

   @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        if (viewType == VIEW_ITEM) {
            holder = new MyViewHolder(inflater.inflate(R.layout.item_view, parent, false));
        } else {
            holder = new MyProgressViewHolder(inflater.inflate(R.layout.item_footer, parent, false));
        }
        return holder;
    }
 @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder) {
            if (((MyViewHolder) holder).tv_name != null)
                ((MyViewHolder) holder).tv_name.setText(mData.get(position));
        } else if (holder instanceof MyProgressViewHolder) {
            if (((MyProgressViewHolder) holder).pb != null)
                ((MyProgressViewHolder) holder).pb.setIndeterminate(true);
        }
    }


    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }


    //根据不同的数据返回不同的viewType
    @Override
    public int getItemViewType(int position) {
        return mData.get(position) != null ? VIEW_ITEM : VIEW_PROG;

    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private final TextView tv_name;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnitemClickListener != null)
                        mOnitemClickListener.onClick(v);
                }
            });
        }

    }

    public class MyProgressViewHolder extends RecyclerView.ViewHolder {

        private final ProgressBar pb;

        public MyProgressViewHolder(View itemView) {
            super(itemView);
            pb = (ProgressBar) itemView.findViewById(R.id.pb);
        }

    }

    //设置数据的方法
    public void setData(List data) {
        mData = data;
    }

    private LoadMoreDataListener mMoreDataListener;

    //加载更多监听方法
    public void setOnMoreDataLoadListener(LoadMoreDataListener onMoreDataLoadListener) {
        mMoreDataListener = onMoreDataLoadListener;
    }

    private RecyclerOnItemClickListener mOnitemClickListener;

    //点击事件监听方法
    public void setOnItemClickListener(RecyclerOnItemClickListener onItemClickListener) {
        mOnitemClickListener = onItemClickListener;
    }
}


 
  
 
  
通过以上几部操作,就可以实现RecyclerView的底部加载更多的功能了,同时我用SwipeRefreshLayout实现了下拉刷新。

今天第一次写技术博客,应该有很多地方写的不够妥当,望各位大神们指点!实现效果如下!

RecyclerView实现底部加载更多功能_第1张图片




你可能感兴趣的:(android)