RecyclerView实现底部载入很多其它功能
Posted blfbuaa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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<String> list = new ArrayList<>(); private List<String> moreData = new ArrayList<>(); private List<String> 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
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.byzk.loadmorerecyclerview.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.byzk.loadmorerecyclerview.MainActivity" tools:showIn="@layout/activity_main"> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/sfl" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/mRecyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:scrollbars="vertical"> </android.support.v7.widget.RecyclerView> </android.support.v4.widget.SwipeRefreshLayout> <TextView android:id="@+id/tv_empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="暂无数据" android:textColor="@color/colorAccent" android:visibility="gone" /> </RelativeLayout>
创建RecyclerView的条目布局 item_view
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:orientation="horizontal" card_view:cardUseCompatPadding="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="80dp" android:background="?android:selectableItemBackground" android:gravity="center"> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="5dp" android:text="Name" android:textColor="@android:color/black" android:textSize="18sp" /> </RelativeLayout> </android.support.v7.widget.CardView>
创建脚布局item_footer
<?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="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="10dp"> <ProgressBar android:id="@+id/pb" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
第三步:创建一个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<String> 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<String> 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实现底部载入很多其它功能的主要内容,如果未能解决你的问题,请参考以下文章
Android实现RecyclerView的下拉刷新和上拉载入很多其它
瀑布流点击载入很多其它(记住tomcat下启动,做过瀑布流的大家预计都知道为啥)