咱們公司目前開發的全部Android APP都是遵循iOS風格設計的,這並非一個好現象。我決定將Android 5.x控件引入最近開發的項目中,使用RecyclerView取代以往使用的ListView、GridView,使用SwipeRefreshLayout取代pull-to-refresh第三方庫,打造更符合Material Design風格的APP。java
本篇博客介紹的就是如何使用SwipeRefreshLayout和RecyclerView實現高仿簡書Android端的下拉刷新和上拉加載更多的效果。android
根據效果圖能夠發現,本案例實現了以下效果:git
第一次進入頁面顯示SwipeRefreshLayout的下拉刷新效果github
當內容鋪滿屏幕時,向下滑動顯示「加載中…」效果並加載更多數據app
當SwipeRefreshLayout正在下拉刷新時,將屏蔽加載更多操做less
當加載更多數據時,屏蔽有可能的重複的上拉操做ide
當向上滑動RecyclerView時,隱藏Toolbar以得到更好的用戶體驗佈局
MainActivitypost
package com.leohan.refresh; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.ButterKnife; import butterknife.InjectView; /** * @author Leo */ public class MainActivity extends AppCompatActivity { @InjectView(R.id.toolbar) Toolbar toolbar; @InjectView(R.id.recyclerView) RecyclerView recyclerView; @InjectView(R.id.SwipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; boolean isLoading; private List<Map<String, Object>> data = new ArrayList<>(); private MyAdapter adapter = new MyAdapter(this, data); private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notice); ButterKnife.inject(this); initView(); initData(); } public void initView() { setSupportActionBar(toolbar); toolbar.setTitle(R.string.notice); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); swipeRefreshLayout.setColorSchemeResources(R.color.blueStatus); swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); } }); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { handler.postDelayed(new Runnable() { @Override public void run() { data.clear(); getData(); } }, 2000); } }); final LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); Log.d("test", "StateChanged = " + newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); Log.d("test", "onScrolled"); int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); if (lastVisibleItemPosition + 1 == adapter.getItemCount()) { Log.d("test", "loading executed"); boolean isRefreshing = swipeRefreshLayout.isRefreshing(); if (isRefreshing) { adapter.notifyItemRemoved(adapter.getItemCount()); return; } if (!isLoading) { isLoading = true; handler.postDelayed(new Runnable() { @Override public void run() { getData(); Log.d("test", "load more completed"); isLoading = false; } }, 1000); } } } }); //添加點擊事件 adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Log.d("test", "item position = " + position); } @Override public void onItemLongClick(View view, int position) { } }); } public void initData() { handler.postDelayed(new Runnable() { @Override public void run() { getData(); } }, 1500); } /** * 獲取測試數據 */ private void getData() { for (int i = 0; i < 6; i++) { Map<String, Object> map = new HashMap<>(); data.add(map); } adapter.notifyDataSetChanged(); swipeRefreshLayout.setRefreshing(false); adapter.notifyItemRemoved(adapter.getItemCount()); } }
RecyclerViewAdapter測試
package com.leohan.refresh; import android.content.Context; import android.support.v7.widget.RecyclerView.Adapter; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class RecyclerViewAdapter extends Adapter<ViewHolder> { private static final int TYPE_ITEM = 0; private static final int TYPE_FOOTER = 1; private Context context; private List data; public interface OnItemClickListener { void onItemClick(View view, int position); void onItemLongClick(View view, int position); } private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public int getItemCount() { return data.size() == 0 ? 0 : data.size() + 1; } @Override public int getItemViewType(int position) { if (position + 1 == getItemCount()) { return TYPE_FOOTER; } else { return TYPE_ITEM; } } public RecyclerViewAdapter(Context context, List data) { this.context = context; this.data = data; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_ITEM) { View view = LayoutInflater.from(context).inflate(R.layout.item_notice, parent, false); return new ItemViewHolder(view); } else if (viewType == TYPE_FOOTER) { View view = LayoutInflater.from(context).inflate(R.layout.item_foot, parent, false); return new FootViewHolder(view); } return null; } @Override public void onBindViewHolder(final ViewHolder holder, int position) { if (holder instanceof ItemViewHolder) { //holder.tv.setText(data.get(position)); if (onItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = holder.getLayoutPosition(); onItemClickListener.onItemClick(holder.itemView, position); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int position = holder.getLayoutPosition(); onItemClickListener.onItemLongClick(holder.itemView, position); return false; } }); } } } static class ItemViewHolder extends ViewHolder { TextView tv; public ItemViewHolder(View view) { super(view); tv = (TextView) view.findViewById(R.id.tv_date); } } static class FootViewHolder extends ViewHolder { public FootViewHolder(View view) { super(view); } } }
item_base.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/margin_10" android:layout_marginRight="@dimen/margin_10" android:foreground="?android:attr/selectableItemBackgroundBorderless" android:layout_marginTop="6dp" android:orientation="vertical" app:cardBackgroundColor="@color/line" app:cardPreventCornerOverlap="true" app:cardUseCompatPadding="true" app:contentPadding="6dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_date" style="@style/NormalTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2015-12-11 12:00" /> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:cardBackgroundColor="@color/white" app:cardPreventCornerOverlap="true" app:cardUseCompatPadding="true" app:contentPadding="10dp"> <TextView android:id="@+id/tv_title" style="@style/SmallGreyTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:maxLines="2" android:text="視線好轉,0729出口開通,0621進口開通。視線好轉,0729出口開通,0621進口開通。" /> </android.support.v7.widget.CardView> </LinearLayout></android.support.v7.widget.CardView>
item_foot.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="40dp" android:gravity="center" android:orientation="horizontal" > <ProgressBar android:layout_marginRight="6dp" android:id="@+id/progressBar" style="?android:attr/progressBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> <TextView style="@style/SmallGreyTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/loading" /> </LinearLayout>
上拉加載更多數據經過監聽RecyclerView的滾動事件RecyclerView.OnScrollListener()實現的,它提供了兩個方法:
/** * 當RecyclerView的滑動狀態改變時觸發 */ public void onScrollStateChanged(RecyclerView recyclerView, int newState){} /** * 當RecyclerView滑動時觸發 * 相似點擊事件的MotionEvent.ACTION_MOVE */ public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
RecyclerView的滑動狀態有以下三種:
/** * The RecyclerView is not currently scrolling. * 手指離開屏幕 */ public static final int SCROLL_STATE_IDLE = 0; /** * The RecyclerView is currently being dragged by outside input such as user touch input. * 手指觸摸屏幕 */ public static final int SCROLL_STATE_DRAGGING = 1; /** * The RecyclerView is currently animating to a final position while not under * outside control. * 手指加速滑動並放開,此時滑動狀態伴隨SCROLL_STATE_IDLE */ public static final int SCROLL_STATE_SETTLING = 2;
因爲簡書APP的上拉加載更多的是在滑動到最後一個item時自動觸發的,與手指是否在屏幕上無關,即與滑動狀態無關。所以,實現這種效果只須要在public void onScrolled(RecyclerView recyclerView, int dx, int dy) 方法中操做,無需關注當時的滑動狀態:
@Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); Log.d("test", "onScrolled"); int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); if (lastVisibleItemPosition + 1 == adapter.getItemCount()) { Log.d("test", "loading executed"); boolean isRefreshing = swipeRefreshLayout.isRefreshing(); if (isRefreshing) { adapter.notifyItemRemoved(adapter.getItemCount()); return; } if (!isLoading) { isLoading = true; handler.postDelayed(new Runnable() { @Override public void run() { getData(); Log.d("test", "load more completed"); isLoading = false; } }, 1000); } } }
若是要實現當且僅當滑動到最後一項而且手指上拉拋出時才執行上拉加載更多效果的話,須要配合onScrollStateChanged(RecyclerView recyclerView, int newState的使用,能夠將代碼改成:
@Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); Log.d("test", "StateChanged = " + newState); if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition + 1 == adapter.getItemCount()) { Log.d("test", "loading executed"); boolean isRefreshing = swipeRefreshLayout.isRefreshing(); if (isRefreshing) { adapter.notifyItemRemoved(adapter.getItemCount()); return; } if (!isLoading) { isLoading = true; handler.postDelayed(new Runnable() { @Override public void run() { getData(); Log.d("test", "load more completed"); isLoading = false; } }, 1000); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); Log.d("test", "onScrolled"); lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); }
加載更多的效果能夠經過item_foot.xml自定義,滑動到最後一項時顯示該item並執行加載更多,當加載數據完畢時須要將該item移除掉
adapter.notifyItemRemoved(adapter.getItemCount());
下面的代碼就是RecyclerView的多個item佈局的實現方法:
@Override public int getItemCount() { return data.size() == 0 ? 0 : data.size() + 1; } @Override public int getItemViewType(int position) { if (position + 1 == getItemCount()) { return TYPE_FOOTER; } else { return TYPE_ITEM; } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_ITEM) { View view = LayoutInflater.from(context).inflate(R.layout.item_base, parent, false); return new ItemViewHolder(view); } else if (viewType == TYPE_FOOTER) { View view = LayoutInflater.from(context).inflate(R.layout.item_foot, parent, false); return new FootViewHolder(view); } return null; }
該案例源碼:https://github.com/leoleohan/RefreshDemo,歡迎Star、Fork。